Skip to content

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.

I benchmarked it as such:

const fs = require('fs');

console.time();
for (let t = 0; t < 100000; ++t) fs.existsSync('./doesnt-exist');
console.timeEnd();
❯ [mael-mbp?] node git:(existssync-no-errors) ✗ ❯ node --version
v11.1.0

❯ [mael-mbp?] node git:(existssync-no-errors) ✗ ❯ node test.js
default: 2543.314ms

❯ [mael-mbp?] node git:(existssync-no-errors) ✗ ❯ ./node test.js
default: 287.442ms

Fixes: https://github.com/nodejs/node/issues/24008

Checklist
  • make -j4 test (UNIX), or vcbuild test (Windows) passes
  • tests and/or benchmarks are included
  • commit message follows commit guidelines

Merge request reports

Loading