How can I synchronously check, using node.js, if a file or directory 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().