test_runner: fix memory leaks in runner

- Close readline interface after child process exits
  Prevents accumulation of event listeners on stderr stream

- Extract watch mode event handler to named function
  Allows proper cleanup when watch mode is aborted

These changes prevent unbounded memory growth in long-running
test suites and watch mode sessions.

PR-URL: https://github.com/nodejs/node/pull/60860
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Moshe Atlow <moshe@atlow.co.il>
This commit is contained in:
Abhishek Kv. Savani authored and Antoine du Hamel committed 2026-01-20 14:36:02 +01:00
1 parent 434fcd7f8f
commit ec1cbbe0b6
1 file changed
+19 -6
+19 -6
View File
@@ -460,6 +460,9 @@ function runTestFile(path, filesWatcher, opts) {
finished(child.stdout, { __proto__: null, signal: t.signal }),
]);
// Close readline interface to prevent memory leak
rl.close();
if (watchMode) {
filesWatcher.runningProcesses.delete(path);
filesWatcher.runningSubtests.delete(path);
@@ -522,7 +525,7 @@ function watchFiles(testFiles, opts) {
}
// Watch for changes in current filtered files
watcher.on('changed', ({ owners, eventType }) => {
const onChanged = ({ owners, eventType }) => {
if (!opts.hasFiles && (eventType === 'rename' || eventType === 'change')) {
const updatedTestFiles = createTestFileList(opts.globPatterns, opts.cwd);
const newFileName = ArrayPrototypeFind(updatedTestFiles, (x) => !ArrayPrototypeIncludes(testFiles, x));
@@ -563,19 +566,29 @@ function watchFiles(testFiles, opts) {
triggerUncaughtException(error, true /* fromPromise */);
}));
}
});
};
watcher.on('changed', onChanged);
// Cleanup function to remove event listener and prevent memory leak
const cleanup = () => {
watcher.removeListener('changed', onChanged);
opts.root.harness.watching = false;
opts.root.postRun();
};
if (opts.signal) {
kResistStopPropagation ??= require('internal/event_target').kResistStopPropagation;
opts.signal.addEventListener(
'abort',
() => {
opts.root.harness.watching = false;
opts.root.postRun();
},
cleanup,
{ __proto__: null, once: true, [kResistStopPropagation]: true },
);
}
// Expose cleanup method for proper resource management
filesWatcher.cleanup = cleanup;
return filesWatcher;
}