From d398d46d808be03c2c5ae98830d583561c145093 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ABl=20Nison?= Date: Sat, 3 Nov 2018 13:04:34 -0700 Subject: [PATCH] fs: makes existsSync stop using errors 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: https://github.com/nodejs/node/issues/24008 --- lib/fs.js | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/lib/fs.js b/lib/fs.js index 89c005375f450e..cdcca13c0e6938 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -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) {