node.jspathdirectoryfilesystemsfs

Node.js check if path is file or directory


I can't seem to get any search results that explain how to do this.

All I want to do is be able to know if a given path is a file or a directory (folder).


Solution

  • The following should tell you. From the docs:

    fs.lstatSync(path_string).isDirectory() 
    

    Objects returned from fs.stat() and fs.lstat() are of this type.

    stats.isFile()
    stats.isDirectory()
    stats.isBlockDevice()
    stats.isCharacterDevice()
    stats.isSymbolicLink() // (only valid with fs.lstat())
    stats.isFIFO()
    stats.isSocket()
    

    NOTE:

    The above solution will throw an Error if; for ex, the file or directory doesn't exist.

    If you want a true or false approach, try fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory(); as mentioned by Joseph in the comments below.