Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -279,8 +279,16 @@ function stat(filename) {
if (result !== undefined) { return result; }
}
const result = internalFsBinding.internalModuleStat(filename);
if (statCache !== null && result >= 0) {
// Only set cache when `internalModuleStat(filename)` succeeds.
if (statCache !== null) {
// Cache both successful results (0 = file, 1 = directory) and negative
// results (libuv error codes, e.g. -ENOENT). Negative results are common
// and repeated during resolution: `tryExtensions` probes several
// non-existent extensions, and bare specifiers walk the `node_modules`
// chain upward stat-ing many parent directories that do not exist. The
// cache is scoped to a single top-level `require` tree (created and torn
// down around `requireDepth === 0`), so caching a negative result carries
// the same bounded staleness window that caching a positive one already
// does.
statCache.set(filename, result);
}
return result;
Expand Down
34 changes: 34 additions & 0 deletions test/parallel/test-module-negative-stat-cache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
'use strict';
require('../common');

// This tests that the CommonJS loader's per-require-tree stat cache also caches
// negative (not-found) results, so a path that is missing when first probed is
// not re-stat-ed for the rest of the require tree.

const assert = require('assert');
const fs = require('fs');
const tmpdir = require('../common/tmpdir');

tmpdir.refresh();

// A module path that does not exist yet.
const generated = tmpdir.resolve('generated.js');

// First probe: the file does not exist -> negative stat, cached.
assert.throws(
() => require(generated),
{ code: 'MODULE_NOT_FOUND' },
'expected the module to be missing before it is created',
);

// Create the file mid-traversal, in the same require tree.
fs.writeFileSync(generated, 'module.exports = 1;');

// Second probe, still in the same tree: the negative result is cached, so the
// loader must serve the cached miss instead of re-stat-ing and observing the
// freshly-created file.
assert.throws(
() => require(generated),
{ code: 'MODULE_NOT_FOUND' },
'a negative stat result must be cached for the rest of the require tree',
);
Loading