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’);
}
});


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');
 }
}

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.


This content originally appeared on DEV Community and was authored by Rajesh Kumar Yadav


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » Node.js : Checking if a file or a directory exists." Rajesh Kumar Yadav | Sciencx - Saturday May 22, 2021, https://www.scien.cx/2021/05/22/node-js-checking-if-a-file-or-a-directory-exists/
HARVARD
Rajesh Kumar Yadav | Sciencx Saturday May 22, 2021 » Node.js : Checking if a file or a directory exists., viewed ,<https://www.scien.cx/2021/05/22/node-js-checking-if-a-file-or-a-directory-exists/>
VANCOUVER
Rajesh Kumar Yadav | Sciencx - » Node.js : Checking if a file or a directory exists. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/05/22/node-js-checking-if-a-file-or-a-directory-exists/
CHICAGO
" » Node.js : Checking if a file or a directory exists." Rajesh Kumar Yadav | Sciencx - Accessed . https://www.scien.cx/2021/05/22/node-js-checking-if-a-file-or-a-directory-exists/
IEEE
" » Node.js : Checking if a file or a directory exists." Rajesh Kumar Yadav | Sciencx [Online]. Available: https://www.scien.cx/2021/05/22/node-js-checking-if-a-file-or-a-directory-exists/. [Accessed: ]
rf:citation
» Node.js : Checking if a file or a directory exists | Rajesh Kumar Yadav | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.