Skip to content

Commit

Permalink
fs: makes existsSync stop using errors
Browse files Browse the repository at this point in the history
The previous implementation of `existsSync` was a try/catch on top
of `accessSync`. While conceptually sound it was a performance problem
when running it repeatedly on non-existing files, because `accessSync`
had to create an `Error` object that was immediatly discarded (because
`existsSync` never reports anything else than `true` / `false`).

This implementation simply checks whether the context would have caused
an exception to be thrown, but doesn't actually create it.

Fixes: nodejs#24008
  • Loading branch information
Maël Nison committed Nov 3, 2018
1 parent 2ea70ea commit d398d46
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -227,12 +227,19 @@ Object.defineProperty(exists, internalUtil.promisify.custom, {
// validation errors to users properly out of compatibility concerns.
// TODO(joyeecheung): deprecate the never-throw-on-invalid-arguments behavior
function existsSync(path) {
let ctx;

try {
fs.accessSync(path, F_OK);
return true;
} catch (e) {
path = toPathIfFileURL(path);
validatePath(path);

ctx = { path };
binding.access(pathModule.toNamespacedPath(path), F_OK, undefined, ctx);
} catch {
return false;
}

return ctx.errno === undefined && ctx.error === undefined;
}

function readFileAfterOpen(err, fd) {
Expand Down

0 comments on commit d398d46

Please sign in to comment.