Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *