How to check if a file exists with Node.js?

Sometimes, we want to check if a file exists with Node.js.

In this article, we’ll look at how to check if a file exists with Node.js.

How to check if a file exists with Node.js?

To check if a file exists with Node.js, we can use the fs.promises.access method.

For instance, we write

const checkFileExists = async (file) => {
  try {
    await fs.promises.access(file, fs.constants.F_OK)
    return true
  } catch (e) {
    return false
  }
}

to define the checkFileExists method.

In it, we call fs.promises.access with the file path string and fs.constants.F_OK to check if we can access the file at the file path.

If it’s successful, we return true.

Otherwise, we return false as we did in the catch block

Conclusion

To check if a file exists with Node.js, we can use the fs.promises.access method.