Synchronously check if a file or directory exists in Node.js

Synchronous operations are good for doing file or directory operations before returning a module. Using fs.existsSync() to check if a file or directory exists or not. Use as shown below.

const fs = require("fs"); // Or `import fs from "fs";` with ESM

if(fs.existsSync(path)) {

// Do something

}

This function was deprecated for several years but now it is no longer deprecated. You can use asynchronous check by using fs.promises.access if you are using async functions or fs.access if not.


try {

await fs.promises.access("somefile");

// The check succeeded

} catch (error) {

// The check failed

}

In a callback use as follows:

fs.access("somefile", error => {

if (!error) {

// The check succeeded

} else {

// The check failed

}

});