I noticed that the official node documentation says something startling about fs.exists
:
\"fs.exists() is an anachronism and exists only
I was searching for a solution to this issue and found that fs.exists and fs.existsSync was deprecated. This seems to work well in my senario
fs.readFile(filename, 'utf8', function(err,data){
// the err variable substitutes for the fs.exists callback function variable
if (!err){
// do what you planned with the file
console.log(data)
}else{
// handle the non-existence of the file
console.log('File does not exist!');
}
});
There is no need to use fs.stat(), because 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.)
You can use new install for this one and continue to use it:
https://github.com/imyller/node-fs-exists-nodeback
npm install fs-exists-nodeback
Because of the second paragraph you quoted.
There is no point in checking whether a file exists, because it could always be deleted right after the check.
existsSync's implementation is like this (v0.10.25):
function (path) {
try {
nullCheck(path);
binding.stat(pathModule._makeLong(path));
return true;
} catch (e) {
return false;
}
}
so if you write program like if(fs.existsSync(thepath)){}
, it is better to change it to if(fs.statSync(thepath)){}
.
I think it because it's redundant. You can check if a file exists by trying to open it. It will give you ENOENT
if it doesn't exist:
> fs.open('foo', 'r', function(err, fd) {
... console.log(err, fd);
...
})
undefined
> { [Error: ENOENT, open 'foo'] errno: 34, code: 'ENOENT', path: 'foo' } undefined