How to check synchronously if a file or directory exists in Node.js?

Sometimes, we want to check synchronously if a file or directory exists in Node.js.

In this article, we’ll look at how to check synchronously if a file or directory exists in Node.js.

How to check synchronously if a file or directory exists in Node.js?

To check synchronously if a file or directory exists in Node.js, we can use the existsSync method.

For instance, we write

const fs = require("fs"); 
if (fs.existsSync(path)) {
  // ...
}

to call fs.existsSync with a path string to check if the path points to a valid file or folder.

It returns true if it does and false otherwise.

Conclusion

To check synchronously if a file or directory exists in Node.js, we can use the existsSync method.