Indicates a recoverable error that a REPLServer can use to support multi-line input.
Node.js module
repl
Not implemented in Bun
Not implemented. Use Bun's built-in REPL (`bun run` with no arguments or `bun repl`).
class Recoverable
- static stackTraceLimit: number
The
Error.stackTraceLimitproperty specifies the number of stack frames collected by a stack trace (whether generated bynew Error().stackorError.captureStackTrace(obj)).The default value is
10but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed.If set to a non-number value, or set to a negative number, stack traces will not capture any frames.
- targetObject: object,constructorOpt?: Function): void;
Create .stack property on a target object
class REPLServer
Instances of
repl.REPLServerare created using the start method or directly using the JavaScriptnewkeyword.import repl from 'node:repl'; const options = { useColors: true }; const firstInstance = repl.start(options); const secondInstance = new repl.REPLServer(options);- readonly completer: Completer | AsyncCompleter
Specified in the REPL options, this is the function to use for custom Tab auto-completion.
- readonly cursor: number
The cursor position relative to
rl.line.This will track where the current cursor lands in the input string, when reading input from a TTY stream. The position of cursor determines the portion of the input string that will be modified as input is processed, as well as the column where the terminal caret will be rendered.
- readonly ignoreUndefined: boolean
Specified in the REPL options, this is a value indicating whether the default
writerfunction should output the result of a command if it evaluates toundefined. - readonly last: any
The last evaluation result from the REPL (assigned to the
_variable inside of the REPL). - readonly lastError: any
The last error raised inside the REPL (assigned to the
_errorvariable inside of the REPL). - readonly line: string
The current input data being processed by node.
This can be used when collecting input from a TTY stream to retrieve the current value that has been processed thus far, prior to the
lineevent being emitted. Once thelineevent has been emitted, this property will be an empty string.Be aware that modifying the value during the instance runtime may have unintended consequences if
rl.cursoris not also controlled.If not using a TTY stream for input, use the
'line'event.One possible use case would be as follows:
const values = ['lorem ipsum', 'dolor sit amet']; const rl = readline.createInterface(process.stdin); const showResults = debounce(() => { console.log( '\n', values.filter((val) => val.startsWith(rl.line)).join(' '), ); }, 300); process.stdin.on('keypress', (c, k) => { showResults(); }); - readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT
Specified in the REPL options, this is a flag that specifies whether the default
evalfunction should execute all JavaScript commands in strict mode or default (sloppy) mode. Possible values are:repl.REPL_MODE_SLOPPY- evaluates expressions in sloppy mode.repl.REPL_MODE_STRICT- evaluates expressions in strict mode. This is equivalent to prefacing every repl statement with'use strict'.
- readonly underscoreErrAssigned: boolean
A value indicating whether the
_errorvariable has been assigned. - readonly useColors: boolean
Specified in the REPL options, this is a value indicating whether the default
writerfunction should include ANSI color styling to REPL output. - readonly useGlobal: boolean
Specified in the REPL options, this is a value indicating whether the default
evalfunction will use the JavaScriptglobalas the context as opposed to creating a new separate context for the REPL instance. - readonly writer: REPLWriter
Specified in the REPL options, this is the function to invoke to format the output of each command before writing to
outputStream. If not specified in the REPL options, this will be a wrapper forutil.inspect. - static captureRejections: boolean
Value: boolean
Change the default
captureRejectionsoption on all newEventEmitterobjects. - readonly static captureRejectionSymbol: typeof captureRejectionSymbol
Value:
Symbol.for('nodejs.rejection')See how to write a custom
rejection handler. - static defaultMaxListeners: number
By default, a maximum of
10listeners can be registered for any single event. This limit can be changed for individualEventEmitterinstances using theemitter.setMaxListeners(n)method. To change the default for allEventEmitterinstances, theevents.defaultMaxListenersproperty can be used. If this value is not a positive number, aRangeErroris thrown.Take caution when setting the
events.defaultMaxListenersbecause the change affects allEventEmitterinstances, including those created before the change is made. However, callingemitter.setMaxListeners(n)still has precedence overevents.defaultMaxListeners.This is not a hard limit. The
EventEmitterinstance will allow more listeners to be added but will output a trace warning to stderr indicating that a "possible EventEmitter memory leak" has been detected. For any singleEventEmitter, theemitter.getMaxListeners()andemitter.setMaxListeners()methods can be used to temporarily avoid this warning:import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.setMaxListeners(emitter.getMaxListeners() + 1); emitter.once('event', () => { // do stuff emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); });The
--trace-warningscommand-line flag can be used to display the stack trace for such warnings.The emitted warning can be inspected with
process.on('warning')and will have the additionalemitter,type, andcountproperties, referring to the event emitter instance, the event's name and the number of attached listeners, respectively. Itsnameproperty is set to'MaxListenersExceededWarning'. - readonly static errorMonitor: typeof errorMonitor
This symbol shall be used to install a listener for only monitoring
'error'events. Listeners installed using this symbol are called before the regular'error'listeners are called.Installing a listener using this symbol does not change the behavior once an
'error'event is emitted. Therefore, the process will still crash if no regular'error'listener is installed. Alias for
rl.close().- event: string,listener: (...args: any[]) => void): this;
events.EventEmitter
- close - inherited from
readline.Interface - line - inherited from
readline.Interface - pause - inherited from
readline.Interface - resume - inherited from
readline.Interface - SIGCONT - inherited from
readline.Interface - SIGINT - inherited from
readline.Interface - SIGTSTP - inherited from
readline.Interface - exit
- reset
event: 'close',listener: () => void): this;events.EventEmitter
- close - inherited from
readline.Interface - line - inherited from
readline.Interface - pause - inherited from
readline.Interface - resume - inherited from
readline.Interface - SIGCONT - inherited from
readline.Interface - SIGINT - inherited from
readline.Interface - SIGTSTP - inherited from
readline.Interface - exit
- reset
event: 'line',listener: (input: string) => void): this;events.EventEmitter
- close - inherited from
readline.Interface - line - inherited from
readline.Interface - pause - inherited from
readline.Interface - resume - inherited from
readline.Interface - SIGCONT - inherited from
readline.Interface - SIGINT - inherited from
readline.Interface - SIGTSTP - inherited from
readline.Interface - exit
- reset
event: 'pause',listener: () => void): this;events.EventEmitter
- close - inherited from
readline.Interface - line - inherited from
readline.Interface - pause - inherited from
readline.Interface - resume - inherited from
readline.Interface - SIGCONT - inherited from
readline.Interface - SIGINT - inherited from
readline.Interface - SIGTSTP - inherited from
readline.Interface - exit
- reset
event: 'resume',listener: () => void): this;events.EventEmitter
- close - inherited from
readline.Interface - line - inherited from
readline.Interface - pause - inherited from
readline.Interface - resume - inherited from
readline.Interface - SIGCONT - inherited from
readline.Interface - SIGINT - inherited from
readline.Interface - SIGTSTP - inherited from
readline.Interface - exit
- reset
event: 'SIGCONT',listener: () => void): this;events.EventEmitter
- close - inherited from
readline.Interface - line - inherited from
readline.Interface - pause - inherited from
readline.Interface - resume - inherited from
readline.Interface - SIGCONT - inherited from
readline.Interface - SIGINT - inherited from
readline.Interface - SIGTSTP - inherited from
readline.Interface - exit
- reset
event: 'SIGINT',listener: () => void): this;events.EventEmitter
- close - inherited from
readline.Interface - line - inherited from
readline.Interface - pause - inherited from
readline.Interface - resume - inherited from
readline.Interface - SIGCONT - inherited from
readline.Interface - SIGINT - inherited from
readline.Interface - SIGTSTP - inherited from
readline.Interface - exit
- reset
event: 'SIGTSTP',listener: () => void): this;events.EventEmitter
- close - inherited from
readline.Interface - line - inherited from
readline.Interface - pause - inherited from
readline.Interface - resume - inherited from
readline.Interface - SIGCONT - inherited from
readline.Interface - SIGINT - inherited from
readline.Interface - SIGTSTP - inherited from
readline.Interface - exit
- reset
event: 'exit',listener: () => void): this;events.EventEmitter
- close - inherited from
readline.Interface - line - inherited from
readline.Interface - pause - inherited from
readline.Interface - resume - inherited from
readline.Interface - SIGCONT - inherited from
readline.Interface - SIGINT - inherited from
readline.Interface - SIGTSTP - inherited from
readline.Interface - exit
- reset
event: 'reset',): this;events.EventEmitter
- close - inherited from
readline.Interface - line - inherited from
readline.Interface - pause - inherited from
readline.Interface - resume - inherited from
readline.Interface - SIGCONT - inherited from
readline.Interface - SIGINT - inherited from
readline.Interface - SIGTSTP - inherited from
readline.Interface - exit
- reset
- close - inherited from
The
replServer.clearBufferedCommand()method clears any command that has been buffered but not yet executed. This method is primarily intended to be called from within the action function for commands registered using thereplServer.defineCommand()method.The
rl.close()method closes theInterfaceinstance and relinquishes control over theinputandoutputstreams. When called, the'close'event will be emitted.Calling
rl.close()does not immediately stop other events (including'line') from being emitted by theInterfaceinstance.- keyword: string,): void;
The
replServer.defineCommand()method is used to add new.-prefixed commands to the REPL instance. Such commands are invoked by typing a.followed by thekeyword. Thecmdis either aFunctionor anObjectwith the following properties:The following example shows two new commands added to the REPL instance:
import repl from 'node:repl'; const replServer = repl.start({ prompt: '> ' }); replServer.defineCommand('sayhello', { help: 'Say hello', action(name) { this.clearBufferedCommand(); console.log(`Hello, ${name}!`); this.displayPrompt(); }, }); replServer.defineCommand('saybye', function saybye() { console.log('Goodbye!'); this.close(); });The new commands can then be used from within the REPL instance:
> .sayhello Node.js User Hello, Node.js User! > .saybye Goodbye!@param keywordThe command keyword (without a leading
.character).@param cmdThe function to invoke when the command is processed.
- preserveCursor?: boolean): void;
The
replServer.displayPrompt()method readies the REPL instance for input from the user, printing the configuredpromptto a new line in theoutputand resuming theinputto accept new input.When multi-line input is being entered, a pipe
'|'is printed rather than the 'prompt'.When
preserveCursoristrue, the cursor placement will not be reset to0.The
replServer.displayPromptmethod is primarily intended to be called from within the action function for commands registered using thereplServer.defineCommand()method. - emit(event: string | symbol,...args: any[]): boolean;
Synchronously calls each of the listeners registered for the event named
eventName, in the order they were registered, passing the supplied arguments to each.Returns
trueif the event had listeners,falseotherwise.import { EventEmitter } from 'node:events'; const myEmitter = new EventEmitter(); // First listener myEmitter.on('event', function firstListener() { console.log('Helloooo! first listener'); }); // Second listener myEmitter.on('event', function secondListener(arg1, arg2) { console.log(`event with parameters ${arg1}, ${arg2} in second listener`); }); // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(`event with parameters ${parameters} in third listener`); }); console.log(myEmitter.listeners('event')); myEmitter.emit('event', 1, 2, 3, 4, 5); // Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // Helloooo! first listener // event with parameters 1, 2 in second listener // event with parameters 1, 2, 3, 4, 5 in third listener Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or
Symbols.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {}); const sym = Symbol('symbol'); myEE.on(sym, () => {}); console.log(myEE.eventNames()); // Prints: [ 'foo', 'bar', Symbol(symbol) ]Returns the real position of the cursor in relation to the input prompt + string. Long input (wrapping) strings, as well as multiple line prompts are included in the calculations.
Returns the current max listener value for the
EventEmitterwhich is either set byemitter.setMaxListeners(n)or defaults to EventEmitter.defaultMaxListeners.The
rl.getPrompt()method returns the current prompt used byrl.prompt().@returnsthe current prompt string
- eventName: string | symbol,listener?: Function): number;
Returns the number of listeners listening for the event named
eventName. Iflisteneris provided, it will return how many times the listener is found in the list of the listeners of the event.@param eventNameThe name of the event being listened for
@param listenerThe event handler function
- eventName: string | symbol): Function[];
Returns a copy of the array of listeners for the event named
eventName.server.on('connection', (stream) => { console.log('someone connected!'); }); console.log(util.inspect(server.listeners('connection'))); // Prints: [ [Function] ] - eventName: string | symbol,listener: (...args: any[]) => void): this;
Alias for
emitter.removeListener(). - on(event: string,listener: (...args: any[]) => void): this;
Adds the
listenerfunction to the end of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing added, and called, multiple times.server.on('connection', (stream) => { console.log('someone connected!'); });Returns a reference to the
EventEmitter, so that calls can be chained.By default, event listeners are invoked in the order they are added. The
emitter.prependListener()method can be used as an alternative to add the event listener to the beginning of the listeners array.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a@param listenerThe callback function
- once(event: string,listener: (...args: any[]) => void): this;
Adds a one-time
listenerfunction for the event namedeventName. The next timeeventNameis triggered, this listener is removed and then invoked.server.once('connection', (stream) => { console.log('Ah, we have our first user!'); });Returns a reference to the
EventEmitter, so that calls can be chained.By default, event listeners are invoked in the order they are added. The
emitter.prependOnceListener()method can be used as an alternative to add the event listener to the beginning of the listeners array.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.once('foo', () => console.log('a')); myEE.prependOnceListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a@param listenerThe callback function
The
rl.pause()method pauses theinputstream, allowing it to be resumed later if necessary.Calling
rl.pause()does not immediately pause other events (including'line') from being emitted by theInterfaceinstance.- event: string,listener: (...args: any[]) => void): this;
Adds the
listenerfunction to the beginning of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing added, and called, multiple times.server.prependListener('connection', (stream) => { console.log('someone connected!'); });Returns a reference to the
EventEmitter, so that calls can be chained.@param listenerThe callback function
- event: string,listener: (...args: any[]) => void): this;
Adds a one-time
listenerfunction for the event namedeventNameto the beginning of the listeners array. The next timeeventNameis triggered, this listener is removed, and then invoked.server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); });Returns a reference to the
EventEmitter, so that calls can be chained.@param listenerThe callback function
- preserveCursor?: boolean): void;
The
rl.prompt()method writes theInterfaceinstances configuredpromptto a new line inoutputin order to provide a user with a new location at which to provide input.When called,
rl.prompt()will resume theinputstream if it has been paused.If the
Interfacewas created withoutputset tonullorundefinedthe prompt is not written.@param preserveCursorIf
true, prevents the cursor placement from being reset to0. - query: string,callback: (answer: string) => void): void;
The
rl.question()method displays thequeryby writing it to theoutput, waits for user input to be provided oninput, then invokes thecallbackfunction passing the provided input as the first argument.When called,
rl.question()will resume theinputstream if it has been paused.If the
Interfacewas created withoutputset tonullorundefinedthequeryis not written.The
callbackfunction passed torl.question()does not follow the typical pattern of accepting anErrorobject ornullas the first argument. Thecallbackis called with the provided answer as the only argument.An error will be thrown if calling
rl.question()afterrl.close().Example usage:
rl.question('What is your favorite food? ', (answer) => { console.log(`Oh, so your favorite food is ${answer}`); });Using an
AbortControllerto cancel a question.const ac = new AbortController(); const signal = ac.signal; rl.question('What is your favorite food? ', { signal }, (answer) => { console.log(`Oh, so your favorite food is ${answer}`); }); signal.addEventListener('abort', () => { console.log('The food question timed out'); }, { once: true }); setTimeout(() => ac.abort(), 10000);@param queryA statement or query to write to
output, prepended to the prompt.@param callbackA callback function that is invoked with the user's input in response to the
query.query: string,callback: (answer: string) => void): void;The
rl.question()method displays thequeryby writing it to theoutput, waits for user input to be provided oninput, then invokes thecallbackfunction passing the provided input as the first argument.When called,
rl.question()will resume theinputstream if it has been paused.If the
Interfacewas created withoutputset tonullorundefinedthequeryis not written.The
callbackfunction passed torl.question()does not follow the typical pattern of accepting anErrorobject ornullas the first argument. Thecallbackis called with the provided answer as the only argument.An error will be thrown if calling
rl.question()afterrl.close().Example usage:
rl.question('What is your favorite food? ', (answer) => { console.log(`Oh, so your favorite food is ${answer}`); });Using an
AbortControllerto cancel a question.const ac = new AbortController(); const signal = ac.signal; rl.question('What is your favorite food? ', { signal }, (answer) => { console.log(`Oh, so your favorite food is ${answer}`); }); signal.addEventListener('abort', () => { console.log('The food question timed out'); }, { once: true }); setTimeout(() => ac.abort(), 10000);@param queryA statement or query to write to
output, prepended to the prompt.@param callbackA callback function that is invoked with the user's input in response to the
query. - eventName: string | symbol): Function[];
Returns a copy of the array of listeners for the event named
eventName, including any wrappers (such as those created by.once()).import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once')); // Returns a new Array with a function `onceWrapper` which has a property // `listener` which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0]; // Logs "log once" to the console and does not unbind the `once` event logFnWrapper.listener(); // Logs "log once" to the console and removes the listener logFnWrapper(); emitter.on('log', () => console.log('log persistently')); // Will return a new Array with a single function bound by `.on()` above const newListeners = emitter.rawListeners('log'); // Logs "log persistently" twice newListeners[0](); emitter.emit('log'); - eventName?: string | symbol): this;
Removes all listeners, or those of the specified
eventName.It is bad practice to remove listeners added elsewhere in the code, particularly when the
EventEmitterinstance was created by some other component or module (e.g. sockets or file streams).Returns a reference to the
EventEmitter, so that calls can be chained. - eventName: string | symbol,listener: (...args: any[]) => void): this;
Removes the specified
listenerfrom the listener array for the event namedeventName.const callback = (stream) => { console.log('someone connected!'); }; server.on('connection', callback); // ... server.removeListener('connection', callback);removeListener()will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specifiedeventName, thenremoveListener()must be called multiple times to remove each instance.Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any
removeListener()orremoveAllListeners()calls after emitting and before the last listener finishes execution will not remove them fromemit()in progress. Subsequent events behave as expected.import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); const callbackA = () => { console.log('A'); myEmitter.removeListener('event', callbackB); }; const callbackB = () => { console.log('B'); }; myEmitter.on('event', callbackA); myEmitter.on('event', callbackB); // callbackA removes listener callbackB but it will still be called. // Internal listener array at time of emit [callbackA, callbackB] myEmitter.emit('event'); // Prints: // A // B // callbackB is now removed. // Internal listener array [callbackA] myEmitter.emit('event'); // Prints: // ABecause listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the
emitter.listeners()method will need to be recreated.When a single function has been added as a handler multiple times for a single event (as in the example below),
removeListener()will remove the most recently added instance. In the example theonce('ping')listener is removed:import { EventEmitter } from 'node:events'; const ee = new EventEmitter(); function pong() { console.log('pong'); } ee.on('ping', pong); ee.once('ping', pong); ee.removeListener('ping', pong); ee.emit('ping'); ee.emit('ping');Returns a reference to the
EventEmitter, so that calls can be chained. The
rl.resume()method resumes theinputstream if it has been paused.- n: number): this;
By default
EventEmitters will print a warning if more than10listeners are added for a particular event. This is a useful default that helps finding memory leaks. Theemitter.setMaxListeners()method allows the limit to be modified for this specificEventEmitterinstance. The value can be set toInfinity(or0) to indicate an unlimited number of listeners.Returns a reference to the
EventEmitter, so that calls can be chained. - prompt: string): void;
The
rl.setPrompt()method sets the prompt that will be written tooutputwheneverrl.prompt()is called. - historyPath: string,): void;
Initializes a history log file for the REPL instance. When executing the Node.js binary and using the command-line REPL, a history file is initialized by default. However, this is not the case when creating a REPL programmatically. Use this method to initialize a history log file when working with REPL instances programmatically.
@param historyPaththe path to the history file
@param callbackcalled when history writes are ready or upon error
): void;Initializes a history log file for the REPL instance. When executing the Node.js binary and using the command-line REPL, a history file is initialized by default. However, this is not the case when creating a REPL programmatically. Use this method to initialize a history log file when working with REPL instances programmatically.
@param callbackcalled when history writes are ready or upon error
- ): void;
The
rl.write()method will write eitherdataor a key sequence identified bykeyto theoutput. Thekeyargument is supported only ifoutputis aTTYtext terminal. SeeTTY keybindingsfor a list of key combinations.If
keyis specified,datais ignored.When called,
rl.write()will resume theinputstream if it has been paused.If the
Interfacewas created withoutputset tonullorundefinedthedataandkeyare not written.rl.write('Delete this!'); // Simulate Ctrl+U to delete the line written previously rl.write(null, { ctrl: true, name: 'u' });The
rl.write()method will write the data to thereadlineInterface'sinputas if it were provided by the user.): void;The
rl.write()method will write eitherdataor a key sequence identified bykeyto theoutput. Thekeyargument is supported only ifoutputis aTTYtext terminal. SeeTTY keybindingsfor a list of key combinations.If
keyis specified,datais ignored.When called,
rl.write()will resume theinputstream if it has been paused.If the
Interfacewas created withoutputset tonullorundefinedthedataandkeyare not written.rl.write('Delete this!'); // Simulate Ctrl+U to delete the line written previously rl.write(null, { ctrl: true, name: 'u' });The
rl.write()method will write the data to thereadlineInterface'sinputas if it were provided by the user. - ): Disposable;
Listens once to the
abortevent on the providedsignal.Listening to the
abortevent on abort signals is unsafe and may lead to resource leaks since another third party with the signal can calle.stopImmediatePropagation(). Unfortunately Node.js cannot change this since it would violate the web standard. Additionally, the original API makes it easy to forget to remove listeners.This API allows safely using
AbortSignals in Node.js APIs by solving these two issues by listening to the event such thatstopImmediatePropagationdoes not prevent the listener from running.Returns a disposable so that it may be unsubscribed from more easily.
import { addAbortListener } from 'node:events'; function example(signal) { let disposable; try { signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); disposable = addAbortListener(signal, (e) => { // Do something when signal is aborted. }); } finally { disposable?.[Symbol.dispose](); } }@returnsDisposable that removes the
abortlistener. - name: string | symbol): Function[];
Returns a copy of the array of listeners for the event named
eventName.For
EventEmitters this behaves exactly the same as calling.listenerson the emitter.For
EventTargets this is the only way to get the event listeners for the event target. This is useful for debugging and diagnostic purposes.import { getEventListeners, EventEmitter } from 'node:events'; { const ee = new EventEmitter(); const listener = () => console.log('Events are fun'); ee.on('foo', listener); console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] } { const et = new EventTarget(); const listener = () => console.log('Events are fun'); et.addEventListener('foo', listener); console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] } - ): number;
Returns the currently set max amount of listeners.
For
EventEmitters this behaves exactly the same as calling.getMaxListenerson the emitter.For
EventTargets this is the only way to get the max event listeners for the event target. If the number of event handlers on a single EventTarget exceeds the max set, the EventTarget will print a warning.import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; { const ee = new EventEmitter(); console.log(getMaxListeners(ee)); // 10 setMaxListeners(11, ee); console.log(getMaxListeners(ee)); // 11 } { const et = new EventTarget(); console.log(getMaxListeners(et)); // 10 setMaxListeners(11, et); console.log(getMaxListeners(et)); // 11 } - emitter: EventEmitter,eventName: string | symbol,options?: StaticEventEmitterIteratorOptions): AsyncIterator<any[]>;
import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo')) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable hereReturns an
AsyncIteratorthat iterateseventNameevents. It will throw if theEventEmitteremits'error'. It removes all listeners when exiting the loop. Thevaluereturned by each iteration is an array composed of the emitted event arguments.An
AbortSignalcan be used to cancel waiting on events:import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ac = new AbortController(); (async () => { const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo', { signal: ac.signal })) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here })(); process.nextTick(() => ac.abort());Use the
closeoption to specify an array of event names that will end the iteration:import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); ee.emit('close'); }); for await (const event of on(ee, 'foo', { close: ['close'] })) { console.log(event); // prints ['bar'] [42] } // the loop will exit after 'close' is emitted console.log('done'); // prints 'done'@returnsAn
AsyncIteratorthat iterateseventNameevents emitted by theemittereventName: string,options?: StaticEventEmitterIteratorOptions): AsyncIterator<any[]>;import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo')) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable hereReturns an
AsyncIteratorthat iterateseventNameevents. It will throw if theEventEmitteremits'error'. It removes all listeners when exiting the loop. Thevaluereturned by each iteration is an array composed of the emitted event arguments.An
AbortSignalcan be used to cancel waiting on events:import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ac = new AbortController(); (async () => { const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo', { signal: ac.signal })) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here })(); process.nextTick(() => ac.abort());Use the
closeoption to specify an array of event names that will end the iteration:import { on, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); ee.emit('close'); }); for await (const event of on(ee, 'foo', { close: ['close'] })) { console.log(event); // prints ['bar'] [42] } // the loop will exit after 'close' is emitted console.log('done'); // prints 'done'@returnsAn
AsyncIteratorthat iterateseventNameevents emitted by theemitter - emitter: EventEmitter,eventName: string | symbol,options?: StaticEventEmitterOptions): Promise<any[]>;
Creates a
Promisethat is fulfilled when theEventEmitteremits the given event or that is rejected if theEventEmitteremits'error'while waiting. ThePromisewill resolve with an array of all the arguments emitted to the given event.This method is intentionally generic and works with the web platform EventTarget interface, which has no special
'error'event semantics and does not listen to the'error'event.import { once, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); process.nextTick(() => { ee.emit('myevent', 42); }); const [value] = await once(ee, 'myevent'); console.log(value); const err = new Error('kaboom'); process.nextTick(() => { ee.emit('error', err); }); try { await once(ee, 'myevent'); } catch (err) { console.error('error happened', err); }The special handling of the
'error'event is only used whenevents.once()is used to wait for another event. Ifevents.once()is used to wait for the 'error'event itself, then it is treated as any other kind of event without special handling:import { EventEmitter, once } from 'node:events'; const ee = new EventEmitter(); once(ee, 'error') .then(([err]) => console.log('ok', err.message)) .catch((err) => console.error('error', err.message)); ee.emit('error', new Error('boom')); // Prints: ok boomAn
AbortSignalcan be used to cancel waiting for the event:import { EventEmitter, once } from 'node:events'; const ee = new EventEmitter(); const ac = new AbortController(); async function foo(emitter, event, signal) { try { await once(emitter, event, { signal }); console.log('event emitted!'); } catch (error) { if (error.name === 'AbortError') { console.error('Waiting for the event was canceled!'); } else { console.error('There was an error', error.message); } } } foo(ee, 'foo', ac.signal); ac.abort(); // Abort waiting for the event ee.emit('foo'); // Prints: Waiting for the event was canceled!eventName: string,options?: StaticEventEmitterOptions): Promise<any[]>;Creates a
Promisethat is fulfilled when theEventEmitteremits the given event or that is rejected if theEventEmitteremits'error'while waiting. ThePromisewill resolve with an array of all the arguments emitted to the given event.This method is intentionally generic and works with the web platform EventTarget interface, which has no special
'error'event semantics and does not listen to the'error'event.import { once, EventEmitter } from 'node:events'; import process from 'node:process'; const ee = new EventEmitter(); process.nextTick(() => { ee.emit('myevent', 42); }); const [value] = await once(ee, 'myevent'); console.log(value); const err = new Error('kaboom'); process.nextTick(() => { ee.emit('error', err); }); try { await once(ee, 'myevent'); } catch (err) { console.error('error happened', err); }The special handling of the
'error'event is only used whenevents.once()is used to wait for another event. Ifevents.once()is used to wait for the 'error'event itself, then it is treated as any other kind of event without special handling:import { EventEmitter, once } from 'node:events'; const ee = new EventEmitter(); once(ee, 'error') .then(([err]) => console.log('ok', err.message)) .catch((err) => console.error('error', err.message)); ee.emit('error', new Error('boom')); // Prints: ok boomAn
AbortSignalcan be used to cancel waiting for the event:import { EventEmitter, once } from 'node:events'; const ee = new EventEmitter(); const ac = new AbortController(); async function foo(emitter, event, signal) { try { await once(emitter, event, { signal }); console.log('event emitted!'); } catch (error) { if (error.name === 'AbortError') { console.error('Waiting for the event was canceled!'); } else { console.error('There was an error', error.message); } } } foo(ee, 'foo', ac.signal); ac.abort(); // Abort waiting for the event ee.emit('foo'); // Prints: Waiting for the event was canceled! - n?: number,): void;
import { setMaxListeners, EventEmitter } from 'node:events'; const target = new EventTarget(); const emitter = new EventEmitter(); setMaxListeners(5, target, emitter);@param nA non-negative number. The maximum number of listeners per
EventTargetevent.@param eventTargetsZero or more {EventTarget} or {EventEmitter} instances. If none are specified,
nis set as the default max for all newly created {EventTarget} and {EventEmitter} objects.
A flag passed in the REPL options. Evaluates expressions in sloppy mode.
A flag passed in the REPL options. Evaluates expressions in strict mode. This is equivalent to prefacing every repl statement with
'use strict'.This is the default "writer" value, if none is passed in the REPL options, and it can be overridden by custom print functions.
The
repl.start()method creates and starts a REPLServer instance.If
optionsis a string, then it specifies the input prompt:import repl from 'node:repl'; // a Unix style prompt repl.start('$ ');
Type definitions
interface REPLCommand
interface ReplOptions
- breakEvalOnSigint?: boolean
Stop evaluating the current piece of code when
SIGINTis received, i.e.Ctrl+Cis pressed. This cannot be used together with a customevalfunction. - eval?: REPLEval
The function to be used when evaluating each given line of input. Default: an async wrapper for the JavaScript
eval()function. Anevalfunction can error withrepl.Recoverableto indicate the input was incomplete and prompt for additional lines. See the custom evaluation functions section for more details. - ignoreUndefined?: boolean
If
true, specifies that the default writer will not output the return value of a command if it evaluates toundefined. - replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT
A flag that specifies whether the default evaluator executes all JavaScript commands in strict mode or default (sloppy) mode. Accepted values are:
repl.REPL_MODE_SLOPPY- evaluates expressions in sloppy mode.repl.REPL_MODE_STRICT- evaluates expressions in strict mode. This is equivalent to prefacing every repl statement with'use strict'.
- terminal?: boolean
If
true, specifies that the output should be treated as a TTY terminal, and have ANSI/VT100 escape codes written to it. Default: checking the value of theisTTYproperty on the output stream upon instantiation. - useColors?: boolean
If
true, specifies that the defaultwriterfunction should include ANSI color styling to REPL output. If a customwriterfunction is provided then this has no effect. - useGlobal?: boolean
If
true, specifies that the default evaluation function will use the JavaScriptglobalas the context as opposed to creating a new separate context for the REPL instance. The node CLI REPL sets this value totrue. - writer?: REPLWriter
The function to invoke to format the output of each command before writing to
output.
interface REPLServerSetupHistoryOptions
- type REPLCommandAction = (this: REPLServer, text: string) => void
- type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void
- type REPLWriter = (this: REPLServer, obj: any) => string