Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save caolan/441157 to your computer and use it in GitHub Desktop.
Save caolan/441157 to your computer and use it in GitHub Desktop.
From 42cb3106c2b616d0357f3f89537ff751b3dbd570 Mon Sep 17 00:00:00 2001
From: Caolan McMahon <[email protected]>
Date: Wed, 16 Jun 2010 19:08:39 +0100
Subject: [PATCH] Update path.exists to return relevant errors from fs.stat
The callback for path.exists now accepts two arguments, an error and
a boolean value which performs the same as before. The error is only
passed from fs.stat if it is something other than 'not found'.
This brings the callback in-line with the convention of returning an
error as the first argument, and allows the identification of errors
which stop the existence of the file from being determined (such as
permissions errors).
path.existsSync has also been updated, and throws whenever an error
would have been returned to the callback.
---
lib/module.js | 2 +-
lib/path.js | 11 +++++++++--
test/simple/test-path.js | 2 +-
3 files changed, 11 insertions(+), 4 deletions(-)
diff --git a/lib/module.js b/lib/module.js
index 2f90052..0c47729 100644
--- a/lib/module.js
+++ b/lib/module.js
@@ -153,7 +153,7 @@ function findModulePath (id, dirs, callback) {
// if async
if (callback) {
- path.exists(location, function (found) {
+ path.exists(location, function (err, found) {
if (found) {
callback(location);
} else {
diff --git a/lib/path.js b/lib/path.js
index 0316f96..48d0846 100644
--- a/lib/path.js
+++ b/lib/path.js
@@ -76,7 +76,13 @@ exports.extname = function (path) {
exports.exists = function (path, callback) {
process.binding('fs').stat(path, function (err, stats) {
- if (callback) callback(err ? false : true);
+ if (callback){
+ // errno 2 -- ENOENT, No such file or directory
+ // don't send 'not found' errors to callback
+ if(err && err.errno == 2) callback(null, false);
+ // return previous default of false if there is an error calling fs.stat
+ else callback(err, err ? false : true);
+ }
});
};
@@ -85,6 +91,7 @@ exports.existsSync = function (path) {
process.binding('fs').stat(path)
return true;
} catch(e){
- return false;
+ if(e && e.errno == 2) return false;
+ throw e;
}
};
diff --git a/test/simple/test-path.js b/test/simple/test-path.js
index 4b05378..61b4b40 100644
--- a/test/simple/test-path.js
+++ b/test/simple/test-path.js
@@ -10,7 +10,7 @@ assert.equal(path.dirname(f).substr(-11), "test/simple");
assert.equal(path.dirname("/a/b"), "/a");
assert.equal(path.dirname("/a"), "/");
assert.equal(path.dirname("/"), "/");
-path.exists(f, function (y) { assert.equal(y, true) });
+path.exists(f, function (err, y) { assert.equal(y, true) });
assert.equal(path.existsSync(f), true);
--
1.7.0.4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment