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

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.