According to the documentation node.js fs.exists() will be deprecated. Their reasoning:
fs.exists() is an anachronism and exists only for historical reasons.
Use fs.existsSync().
fs.existsSync() has not been deprecated.
https://nodejs.org/api/fs.html#fs_fs_existssync_path
fs.existsSync(path)
Added in: v0.1.21 path | Synchronous version of fs.exists(). Returns true if the file exists, false otherwise.
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.)
The io.js docs mention the use of fs.stat()
or fs.access()
in place of fs.exists()
.
Here is an example using fs.stat
, but handling errors correctly as well:
async function fileExists(filename) {
try {
await fs.promises.stat(filename);
return true;
} catch (err) {
if (err.code === 'ENOENT') {
return false;
} else {
throw err;
}
}
}
Here is example by using fs.stat
:-
fs.stat('mycustomfile.csv', function (err, stats) {
console.log(stats);//here we got all information of file in stats variable
if (err) {
return console.error(err);
}
fs.unlink('mycustomfile.csv',function(err){
if(err) return console.log(err);
console.log('file deleted successfully');
});
});