Categories
JavaScript Answers

How to check if path is file or directory with Node.js?

Spread the love

Sometimes, we want to check if path is file or directory with Node.js.

In this article, we’ll look at how to check if path is file or directory with Node.js.

How to check if path is file or directory with Node.js?

To check if path is file or directory with Node.js, we can use the fs.lstat with the isDirectory method.

For instance, we write

(await fs.lstat(pathString)).isDirectory() 

to call fs.lstat with the pathString to return a promise which resolves to the stat object.

Then we call isDirectory on the stat object to check if the pathString points to a directory.

To check if the pathString points to a file, we can use the isFile method.

For instance, we write

(await fs.lstat(pathString)).isFile() 

Conclusion

To check if path is file or directory with Node.js, we can use the fs.lstat with the isDirectory 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 *