This content originally appeared on DEV Community and was authored by Rajesh Kumar Yadav
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');
}
});
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');
}
}
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.
Node.js : Determining the line count of a text file
Rajesh Kumar Yadav ・ May 20 ・ 1 min read
Node.js : Reading a file line by line
Rajesh Kumar Yadav ・ May 19 ・ 1 min read
Node.js : Reading from a file synchronously
Rajesh Kumar Yadav ・ May 12 ・ 1 min read
Node.js : Checking if a file or a directory exists
Rajesh Kumar Yadav ・ May 22 ・ 1 min read
Node.js : Check Permissions of a File or Directory
Rajesh Kumar Yadav ・ May 22 ・ 2 min read
This content originally appeared on DEV Community and was authored by Rajesh Kumar Yadav
Rajesh Kumar Yadav | Sciencx (2021-05-22T13:44:07+00:00) Node.js : Checking if a file or a directory exists. Retrieved from https://www.scien.cx/2021/05/22/node-js-checking-if-a-file-or-a-directory-exists/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.