Permalink
Browse files

fs: add errback style support to exists()

fs.exists() does not currently support Node's standard
callback signature. This commit adds errback support while
maintaining backwards compatibility. Closes nodejs#8369.
  • Loading branch information...
cjihrig committed Sep 21, 2014
1 parent 7c04197 commit aeb381ccf6f72546e4ad1a3615d29f52f49dacf4
Showing with 30 additions and 2 deletions.
  1. +9 −1 doc/api/fs.markdown
  2. +11 −1 lib/fs.js
  3. +10 −0 test/simple/test-fs-exists.js
@@ -642,12 +642,20 @@ callback, and have some fallback logic if it is null.
## fs.exists(path, callback)
Test whether or not the given path exists by checking with the file system.
Then call the `callback` argument with either true or false. Example:
Then call the `callback` argument with either true or false. Both of the
following examples work (notice the different callback function arguments):
fs.exists('/etc/passwd', function (exists) {
util.debug(exists ? "it's there" : "no passwd!");
});
fs.exists('/etc/passwd', function (error, exists) {
if (error)
return console.error(error);
util.debug(exists ? "it's there" : "no passwd!");
});
`fs.exists()` is an anachronism and exists only for historical reasons.
There should almost never be a reason to use it in your own code.
@@ -184,7 +184,17 @@ fs.exists = function(path, callback) {
if (!nullCheck(path, cb)) return;
binding.stat(pathModule._makeLong(path), cb);
function cb(err, stats) {
if (callback) callback(err ? false : true);
if (callback) {
var exists = err ? false : true;
// If the callback is passed more than one argument, then call back
// with error and exists. Otherwise, use the legacy behavior, and only
// call back with exists.
if (callback.length > 1)
callback(err, exists);
else
callback(exists);
}
}
};
@@ -34,6 +34,16 @@ fs.exists(f + '-NO', function(y) {
doesNotExist = y;
});
fs.exists(f, function(error, exists) {
assert(!error);
assert(exists);
});
fs.exists(f + '-NO', function(error, exists) {
assert(error);
assert(!exists);
});
assert(fs.existsSync(f));
assert(!fs.existsSync(f + '-NO'));

0 comments on commit aeb381c

Please sign in to comment.