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

Rajesh Kumar Yadav - May 22 '21 - - Dev Community

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .