Skip to content

Commit 1d02416

Browse files
committed
watch: watch for missing dependencies
1 parent f313b39 commit 1d02416

File tree

6 files changed

+77
-20
lines changed

6 files changed

+77
-20
lines changed

lib/internal/modules/cjs/loader.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ const {
2828
ArrayPrototypeIncludes,
2929
ArrayPrototypeIndexOf,
3030
ArrayPrototypeJoin,
31+
ArrayPrototypeMap,
3132
ArrayPrototypePush,
3233
ArrayPrototypeSlice,
3334
ArrayPrototypeSplice,
@@ -191,7 +192,13 @@ function updateChildren(parent, child, scan) {
191192

192193
function reportModuleToWatchMode(filename) {
193194
if (shouldReportRequiredModules && process.send) {
194-
process.send({ 'watch:require': filename });
195+
process.send({ 'watch:require': [filename] });
196+
}
197+
}
198+
199+
function reportModuleNotFoundToWatchMode(basePath, extensions) {
200+
if (shouldReportRequiredModules && process.send) {
201+
process.send({ 'watch:require': ArrayPrototypeMap(extensions, (ext) => path.resolve(`${basePath}${ext}`)) });
195202
}
196203
}
197204

@@ -648,6 +655,7 @@ Module._findPath = function(request, paths, isMain) {
648655
Module._pathCache[cacheKey] = filename;
649656
return filename;
650657
}
658+
reportModuleNotFoundToWatchMode(basePath, ArrayPrototypeConcat([''], exts));
651659
}
652660

653661
return false;

lib/internal/modules/esm/loader.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -463,7 +463,7 @@ class ESMLoader {
463463
);
464464

465465
if (process.env.WATCH_REPORT_DEPENDENCIES && process.send) {
466-
process.send({ 'watch:import': url });
466+
process.send({ 'watch:import': [url] });
467467
}
468468

469469
const job = new ModuleJob(

lib/internal/modules/esm/resolve.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,9 @@ function finalizeResolution(resolved, base, preserveSymlinks) {
254254
err.url = String(resolved);
255255
throw err;
256256
} else if (!stats.isFile()) {
257+
if (process.env.WATCH_REPORT_DEPENDENCIES && process.send) {
258+
process.send({ 'watch:require': [path || resolved.pathname] });
259+
}
257260
throw new ERR_MODULE_NOT_FOUND(
258261
path || resolved.pathname, base && fileURLToPath(base), 'module');
259262
}

lib/internal/watch_mode/files_watcher.js

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
'use strict';
22

33
const {
4+
ArrayIsArray,
5+
ArrayPrototypeForEach,
46
SafeMap,
57
SafeSet,
68
StringPrototypeStartsWith,
@@ -94,6 +96,7 @@ class FilesWatcher extends EventEmitter {
9496
}
9597

9698
filterFile(file) {
99+
if (!file) return;
97100
if (supportsRecursiveWatching) {
98101
this.watchPath(dirname(file));
99102
} else {
@@ -109,11 +112,11 @@ class FilesWatcher extends EventEmitter {
109112
}
110113
child.on('message', (message) => {
111114
try {
112-
if (message['watch:require']) {
113-
this.filterFile(message['watch:require']);
115+
if (ArrayIsArray(message['watch:require'])) {
116+
ArrayPrototypeForEach(message['watch:require'], (file) => this.filterFile(file));
114117
}
115-
if (message['watch:import']) {
116-
this.filterFile(fileURLToPath(message['watch:import']));
118+
if (ArrayIsArray(message['watch:import'])) {
119+
ArrayPrototypeForEach(message['watch:import'], (file) => this.filterFile(fileURLToPath(file)));
117120
}
118121
} catch {
119122
// Failed watching file. ignore

test/fixtures/watch-mode/ipc.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ const tmpdir = require('../../common/tmpdir');
66
const tmpfile = path.join(tmpdir.path, 'file');
77
fs.writeFileSync(tmpfile, '');
88

9-
process.send({ 'watch:require': path.resolve(__filename) });
10-
process.send({ 'watch:import': url.pathToFileURL(path.resolve(__filename)).toString() });
11-
process.send({ 'watch:import': url.pathToFileURL(tmpfile).toString() });
12-
process.send({ 'watch:import': new URL('http://invalid.com').toString() });
9+
process.send({ 'watch:require': [path.resolve(__filename)] });
10+
process.send({ 'watch:import': [url.pathToFileURL(path.resolve(__filename)).toString()] });
11+
process.send({ 'watch:import': [url.pathToFileURL(tmpfile).toString()] });
12+
process.send({ 'watch:import': [new URL('http://invalid.com').toString()] });

test/sequential/test-watch-mode.mjs

Lines changed: 53 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@ import { once } from 'node:events';
1313
if (common.isIBMi)
1414
common.skip('IBMi does not support `fs.watch()`');
1515

16+
function deferred() {
17+
let res;
18+
const promise = new Promise((resolve) => res = resolve);
19+
return { resolve: res, promise };
20+
}
21+
1622
function restart(file) {
1723
// To avoid flakiness, we save the file repeatedly until test is done
1824
writeFileSync(file, readFileSync(file));
@@ -59,8 +65,8 @@ async function spawnWithRestarts({
5965
}
6066

6167
let tmpFiles = 0;
62-
function createTmpFile(content = 'console.log("running");') {
63-
const file = path.join(tmpdir.path, `${tmpFiles++}.js`);
68+
function createTmpFile(content = 'console.log("running");', ext = '.js') {
69+
const file = path.join(tmpdir.path, `${tmpFiles++}${ext}`);
6470
writeFileSync(file, content);
6571
return file;
6672
}
@@ -74,6 +80,25 @@ function assertRestartedCorrectly({ stdout, messages: { inner, completed, restar
7480
assert.deepStrictEqual(lines.slice(-end.length), end);
7581
}
7682

83+
async function failWriteSucceed({ file, watchedFile }) {
84+
let stdout = '';
85+
const notFound = deferred();
86+
const completed = deferred();
87+
const child = spawn(execPath, ['--watch', '--no-warnings', file], { encoding: 'utf8' });
88+
89+
child.stdout.on('data', (data) => {
90+
stdout += data;
91+
if (data.toString().startsWith('Failed running')) notFound.resolve();
92+
if (data.toString().startsWith('Completed running')) completed.resolve();
93+
});
94+
95+
await notFound.promise;
96+
writeFileSync(watchedFile, 'console.log("test has ran");');
97+
await completed.promise;
98+
child.kill();
99+
assert.match(stdout, /test has ran/);
100+
}
101+
77102
tmpdir.refresh();
78103

79104
// Warning: this suite can run safely with concurrency: true
@@ -104,14 +129,6 @@ describe('watch mode', { concurrency: true, timeout: 60_0000 }, () => {
104129
});
105130
});
106131

107-
it('should not watch when running an non-existing file', async () => {
108-
const file = fixtures.path('watch-mode/non-existing.js');
109-
const { stderr, stdout } = await spawnWithRestarts({ file, restarts: 0 });
110-
111-
assert.match(stderr, /code: 'MODULE_NOT_FOUND'/);
112-
assert.strictEqual(stdout, `Failed running ${inspect(file)}\n`);
113-
});
114-
115132
it('should watch when running an non-existing file - when specified under --watch-path', {
116133
skip: !common.isOSX && !common.isWindows
117134
}, async () => {
@@ -220,4 +237,30 @@ describe('watch mode', { concurrency: true, timeout: 60_0000 }, () => {
220237
messages: { restarted: `Restarting ${inspect(file)}`, completed: `Completed running ${inspect(file)}` },
221238
});
222239
});
240+
241+
it('should not watch when running an missing file', async () => {
242+
const nonExistingfile = path.join(tmpdir.path, `${tmpFiles++}.js`);
243+
await failWriteSucceed({ file: nonExistingfile, watchedFile: nonExistingfile });
244+
});
245+
246+
it('should not watch when running an missing mjs file', async () => {
247+
const nonExistingfile = path.join(tmpdir.path, `${tmpFiles++}.mjs`);
248+
await failWriteSucceed({ file: nonExistingfile, watchedFile: nonExistingfile });
249+
});
250+
251+
it('should watch changes to previously missing dependency', async () => {
252+
const dependency = path.join(tmpdir.path, `${tmpFiles++}.js`);
253+
const relativeDependencyPath = `./${path.basename(dependency)}`;
254+
const dependant = createTmpFile(`console.log(require('${relativeDependencyPath}'))`);
255+
256+
await failWriteSucceed({ file: dependant, watchedFile: dependency });
257+
});
258+
259+
it('should watch changes to previously missing ESM dependency', async () => {
260+
const dependency = path.join(tmpdir.path, `${tmpFiles++}.mjs`);
261+
const relativeDependencyPath = `./${path.basename(dependency)}`;
262+
const dependant = createTmpFile(`import '${relativeDependencyPath}'`, '.mjs');
263+
264+
await failWriteSucceed({ file: dependant, watchedFile: dependency });
265+
});
223266
});

0 commit comments

Comments
 (0)