Skip to content

Commit c3aba6c

Browse files
committed
modules: fix repl require calling the same file again
This makes sure multiple require calls will not fail in case a file was created after the first attempt.
1 parent e4e2b0c commit c3aba6c

File tree

2 files changed

+34
-7
lines changed

2 files changed

+34
-7
lines changed

lib/internal/modules/cjs/loader.js

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -86,14 +86,15 @@ const {
8686
const isWindows = process.platform === 'win32';
8787

8888
let requireDepth = 0;
89-
let statCache = new Map();
89+
let statCache = null;
9090
function stat(filename) {
9191
filename = path.toNamespacedPath(filename);
92-
if (statCache === null) statCache = new Map();
93-
let result = statCache.get(filename);
94-
if (result !== undefined) return result;
95-
result = internalModuleStat(filename);
96-
statCache.set(filename, result);
92+
if (statCache !== null) {
93+
const result = statCache.get(filename);
94+
if (result !== undefined) return result;
95+
}
96+
const result = internalModuleStat(filename);
97+
if (statCache !== null) statCache.set(filename, result);
9798
return result;
9899
}
99100

@@ -196,7 +197,7 @@ Module._debug = deprecate(debug, 'Module._debug is deprecated.', 'DEP0077');
196197
// -> a.<ext>
197198
// -> a/index.<ext>
198199

199-
// check if the directory is a package.json dir
200+
// Check if the directory is a package.json dir.
200201
const packageMainCache = Object.create(null);
201202

202203
function readPackage(requestPath) {
@@ -830,6 +831,7 @@ Module.prototype._compile = function(content, filename) {
830831
const exports = this.exports;
831832
const thisValue = exports;
832833
const module = this;
834+
if (requireDepth === 0) statCache = new Map();
833835
if (inspectorWrapper) {
834836
result = inspectorWrapper(compiledWrapper, thisValue, exports,
835837
require, module, filename, dirname);
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const assert = require('assert');
5+
6+
const spawn = require('child_process').spawn;
7+
// Use -i to force node into interactive mode, despite stdout not being a TTY
8+
const child = spawn(process.execPath, ['-i']);
9+
10+
let out = '';
11+
const input = "try { require('./non-existent.json'); } catch {} " +
12+
"require('fs').writeFileSync('./non-existent.json', '1');" +
13+
"require('./non-existent.json');";
14+
15+
child.stderr.on('data', common.mustNotCall());
16+
17+
child.stdout.setEncoding('utf8');
18+
child.stdout.on('data', (c) => {
19+
out += c;
20+
});
21+
child.stdout.on('end', common.mustCall(() => {
22+
assert.strictEqual(out, '> 1\n> ');
23+
}));
24+
25+
child.stdin.end(input);

0 commit comments

Comments
 (0)