DEV Community

Rajesh Kumar Yadav
Rajesh Kumar Yadav Subscriber

Posted on • Edited on

Node.js : Checking if a file or a directory exists

Asynchronously



var fs = require('fs');
fs.stat('path/to/file', function(err) {
 if (!err) {
 console.log('file or directory exists');
 }
 else if (err.code === 'ENOENT') {
 console.log('file or directory does not exist');
 }
});


Enter fullscreen mode Exit fullscreen mode

Synchronously

Here, we must wrap the function call in a try/catch block to handle error.



var fs = require('fs');
try {
 fs.statSync('path/to/file');
 console.log('file or directory exists');
}
catch (err) {
 if (err.code === 'ENOENT') {
 console.log('file or directory does not exist');
 }
}


Enter fullscreen mode Exit fullscreen mode

Buy Me A Coffee

With all that being said, I highly recommend you keep learning!

Thank you for reading this article. Please feel free to connect with me on LinkedIn and Twitter.

Top comments (2)

Collapse
 
senthilmpro profile image
Senthil Muthuvel • Edited

Doesn't fs has "fs.existsSync()" or fs.exists() already to do that? Why you want to use stats method?

Collapse
 
hunterkohler profile image
Hunter Kohler

Well, fs.exists() is now deprecated, and fs.existsSync() is synchronous, so you have to do something. If you only need to check if something exists fs.access() or fs.promises.access() is the way to go. The real reason to not use fs.exists() (or check if the file exists at all) is to avoid a race condition. It's much better to catch the error of a failed call to read or write to a file. Check out what the Node.JS documentation says about this under the fs.access() section

Do not use fs.access() to check for the accessibility of a file before calling fs.open(), fs.readFile() or fs.writeFile(). Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.

Later:

In general, check for the accessibility of a file only if the file will not be used directly, for example when its accessibility is a signal from another process.