node: how to determine if a path is a file or directory



~1 min read


125 words

When using Node, it’s often necessary to know if the path you’re referencing is a file or directory. If you don’t handle these cases, it’s quite easy to call a method that expects one or the other and blows up if it doesn’t get what it wants.

For example:

const file = await fs.readFile("/path/to/directory")

To avoid this problem, we can use stat or lstat on the fs module.

These are (nearly) identical:

[fsPromises.lstat() is e]quivalent to fsPromises.stat() unless path refers to a symbolic link, in which case the link itself is stat-ed, not the file that it refers to. Refer to the POSIX lstat(2) document for more detail.

+ const isFile = await fs.lstat('/path/to/directory').isFile()
const file = isFile await fs.readFile('/path/to/directory');

Related Posts
  • Node: Async filtering

  • Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!