Categories
JavaScript Answers Nodejs

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *