Search code examples
node.jsfiledirectoryfilesystemsfile-type

How to determine if file system path is directory or file?


I'm looking to determine if a file system path is directory or file. I'm not looking to checking for the type an existing path. I'm trying to determine if the path function argument string is a referring to a directory or file.

How do I make a distinction between a file and a directory when this:

/Users/thomas/Desktop/node

The following path could refer to a directory node, or a file node without an extension.

I was thinking about using a trailing / to connote directory.

So this would mean a directory:

/Users/thomas/Desktop/node/

And this would mean a file:

/Users/thomas/Desktop/node

However node's path methods like .resolve() and .join() do not take into consideration the trailing / and always remove it. So is this good practice?


Solution

  • There is no way to check if an arbitrary string is a directory or file if it does not exist.

    However for existing paths, you can use fs.stat() on the path, which will give you an object that has methods for checking the path type (e.g. isDirectory(), isFile(), etc).