How to get a directory from a file path or URL with JavaScript?

Sometimes, we want to get a directory from a file path or URL with JavaScript.

In this article, we’ll look at how to get a directory from a file path or URL with JavaScript.

How to get a directory from a file path or URL with JavaScript?

To get a directory from a file path or URL with JavaScript, we can use the path.dirname method.

For instance, we write:

const path = require('path')
const dirName = path.dirname('/this/is/a/path/to/a/file');
console.log(dirName)

We call path.dirname with a path to get the directory path.

Therefore, dirName is '/this/is/a/path/to/a'.

Conclusion

To get a directory from a file path or URL with JavaScript, we can use the path.dirname method.