node: checking if a file/directory exists

2020-08-10

 | 

~2 min read

 | 

311 words

There are a number of ways to check if a file or directory exists in Node, but one of the simplest is the synchronous existsSync method on the fs module. This method returns a boolean value reflecting whether the path exists or not.

It’s worth noting that fs.exists() has been deprecated due to callback incompatibility, however fs.existsSync does not use a callback and therefore is still acceptable.

Example

const fs = require("fs")

if (fs.existsSync("/etc/passwd")) {
  console.log("The path exists.")
} else {
  console.log("The path does not exist.")
}

While this works, interestingly, for checks like this, it’s not the recommended approach:

To check if a file exists without manipulating it afterwards, fs.access() is recommended.

Unlike exists, which determines whether a target is present, access checks for the caller’s access by testing permissions for the file/directory specified by the path argument. If the target will be modified, i.e. the access call precedes a fs.open, fs.write, or fs.read call, this can create a race condition and the recommendation is to simply call those methods directly and handle the error if the file/directory does not exist.1

The example of checking for a file:

const fs = require("fs")

const path = "/etc/passwd"

fs.access(path, (err) => {
  if (!err) {
    console.log("file exists")
  } else {
    console.log("file does not exist")
  }
})

The example of checking for a file with specific permissions (source):

// Check if the file exists in the current directory, and if it is writable.
fs.access(file, fs.constants.F_OK | fs.constants.W_OK, (err) => {
  if (err) {
    console.error(
      `${file} ${err.code === "ENOENT" ? "does not exist" : "is read-only"}`,
    )
  } else {
    console.log(`${file} exists, and it is writable`)
  }
})

Footnotes

  • 1 For more context as well as some useful examples of what to do (and what not to do), see the Node documentation on fs.access.


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!