Files
node/test/parallel/test-repl-history-init-fail-leak.js
sangwook 71b36ee68a repl: fix FileHandle leak in history initialization
Ensure that the history file handle is closed if initialization fails or
flushing throws an error. This prevents ERR_INVALID_STATE errors where
a FileHandle object is closed during garbage collection.

PR-URL: https://github.com/nodejs/node/pull/61706
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Anna Henningsen <anna@addaleax.net>
2026-02-09 10:46:26 +00:00

57 lines
1.3 KiB
JavaScript

'use strict';
// Flags: --expose-internals
const common = require('../common');
const fs = require('fs');
const path = require('path');
const { ReplHistory } = require('internal/repl/history');
const assert = require('assert');
const tmpdir = require('../common/tmpdir');
tmpdir.refresh();
const historyPath = path.join(tmpdir.path, '.node_repl_history');
fs.writeFileSync(historyPath, 'dummy\n');
const originalOpen = fs.promises.open;
let closeCalled = false;
fs.promises.open = async (filepath, flags, mode) => {
const handle = await originalOpen(filepath, flags, mode);
if (flags === 'r+' && filepath === historyPath) {
handle.truncate = async (len) => {
throw new Error('Mock truncate error');
};
const originalClose = handle.close;
handle.close = async () => {
closeCalled = true;
return originalClose.call(handle);
};
}
return handle;
};
const context = {
historySize: 30,
on: () => {},
once: () => {},
emit: () => {},
pause: () => {},
resume: () => {},
off: () => {},
line: '',
_historyPrev: () => {},
_writeToOutput: () => {}
};
const history = new ReplHistory(context, { filePath: historyPath });
history.initialize(common.mustCall((err) => {
assert.strictEqual(err, null);
assert.strictEqual(closeCalled, true);
}));