Instances of the readline.Interface class are constructed using the readline.createInterface() method. Every instance is associated with a single input Readable stream and a single output Writable stream. The output stream is used to print prompts for user input that arrives on, and is read from, the input stream.
class
readline.Interface
class Interface
- 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 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(); }); - event: string | symbol,...args: any[]): void;
The
Symbol.for('nodejs.rejection')method is called in case a promise rejection happens when emitting an event andcaptureRejectionsis enabled on the emitter. It is possible to useevents.captureRejectionSymbolin place ofSymbol.for('nodejs.rejection').import { EventEmitter, captureRejectionSymbol } from 'node:events'; class MyClass extends EventEmitter { constructor() { super({ captureRejections: true }); } [captureRejectionSymbol](err, event, ...args) { console.log('rejection happened for', event, 'with', err, ...args); this.destroy(err); } destroy(err) { // Tear the resource down here. } } Alias for
rl.close().- eventName: E,): this;
Alias for
emitter.on(eventName, listener).eventName: string | symbol,listener: (...args: any[]) => void): this;Alias for
emitter.on(eventName, listener). 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.- eventName: E,): 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 listeneremit(eventName: 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.
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 toevents.defaultMaxListeners.The
rl.getPrompt()method returns the current prompt used byrl.prompt().@returnsthe current prompt string
- eventName: E,): 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,listener?: (...args: any[]) => void): 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: E
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): (...args: any[]) => void[];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: E,): this;
Alias for
emitter.removeListener().off(eventName: string | symbol,listener: (...args: any[]) => void): this;Alias for
emitter.removeListener(). - eventName: E,): 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 eventNameThe name of the event.
@param listenerThe callback function
on(eventName: string | symbol,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 eventNameThe name of the event.
@param listenerThe callback function
- eventName: E,): 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 eventNameThe name of the event.
@param listenerThe callback function
once(eventName: string | symbol,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 eventNameThe name of the event.
@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.- eventName: E,): 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 eventNameThe name of the event.
@param listenerThe callback function
eventName: string | symbol,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 eventNameThe name of the event.
@param listenerThe callback function
- eventName: E,): 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 eventNameThe name of the event.
@param listenerThe callback function
eventName: string | symbol,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 eventNameThe name of the event.
@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: E
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): (...args: any[]) => void[];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?: E): 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): 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: E,): 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 indexes 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.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 indexes 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. - ): 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.