diff --git a/lib/internal/repl/history.js b/lib/internal/repl/history.js index d05bb19d733a22..0e2a83594c0cd4 100644 --- a/lib/internal/repl/history.js +++ b/lib/internal/repl/history.js @@ -58,6 +58,7 @@ const kResolveHistoryPath = Symbol('_kResolveHistoryPath'); const kReplHistoryMessage = Symbol('_kReplHistoryMessage'); const kFlushHistory = Symbol('_kFlushHistory'); const kGetHistoryPath = Symbol('_kGetHistoryPath'); +const kCloseHandle = Symbol('_kCloseHandle'); class ReplHistory { constructor(context, options) { @@ -393,13 +394,28 @@ class ReplHistory { } this[kContext].off('line', this[kOnLine].bind(this)); + await this[kCloseHandle](); + } + + async [kCloseHandle]() { if (this[kHistoryHandle] !== null) { + const handle = this[kHistoryHandle]; + this[kHistoryHandle] = null; try { - await this[kHistoryHandle].close(); + await handle.close(); } catch (err) { debug('Error closing history file:', err); } } + this[kContext].emit('historyHandleClosed'); + } + + /** + * Closes the history file handle. + * @returns {Promise} + */ + closeHandle() { + return this[kCloseHandle](); } [kReplHistoryMessage]() { diff --git a/lib/repl.js b/lib/repl.js index 5ad9e4fbb1506f..c9d3723e3a40ed 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -1039,12 +1039,20 @@ class REPLServer extends Interface { this[kBufferedCommandSymbol] = ''; } close() { - if (this.terminal && this.historyManager.isFlushing && !this._closingOnFlush) { + if (this.terminal && this.historyManager?.isFlushing && !this._closingOnFlush) { this._closingOnFlush = true; - this.once('flushHistory', () => super.close()); + this.once('flushHistory', () => this.close()); return; } + // Ensure the history file handle is closed before completing + if (this.terminal && this.historyManager?.closeHandle && !this._historyHandleClosed) { + this._historyHandleClosed = true; + this.historyManager.closeHandle().then(() => { + process.nextTick(() => super.close()); + }); + return; + } process.nextTick(() => super.close()); } createContext() {