How can I synchronously check, using node.js, if a file or directory exists?
Chances are, if you want to know if a file exists, you plan to require it if it does.
function getFile(path){
try{
return require(path);
}catch(e){
return false;
}
}
Some answers here says that fs.exists
and fs.existsSync
are both deprecated. According to the docs this is no more true. Only fs.exists
is deprected now:
Note that fs.exists() is deprecated, but fs.existsSync() is not. (The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback.)
So you can safely use fs.existsSync() to synchronously check if a file exists.
updated asnwer for those people 'correctly' pointing out it doesnt directly answer the question, more bring an alternative option.
fs.existsSync('filePath')
also see docs here.
Returns true if the path exists, false otherwise.
In an async context you could just write the async version in sync method with using the await
keyword. You can simply turn the async callback method into an promise like this:
function fileExists(path){
return new Promise((resolve, fail) => fs.access(path, fs.constants.F_OK,
(err, result) => err ? fail(err) : resolve(result))
//F_OK checks if file is visible, is default does no need to be specified.
}
async function doSomething() {
var exists = await fileExists('filePath');
if(exists){
console.log('file exists');
}
}
the docs on access().