1# Readline 2 3<!--introduced_in=v0.10.0--> 4 5> Stability: 2 - Stable 6 7<!-- source_link=lib/readline.js --> 8 9The `node:readline` module provides an interface for reading data from a 10[Readable][] stream (such as [`process.stdin`][]) one line at a time. 11 12To use the promise-based APIs: 13 14```mjs 15import * as readline from 'node:readline/promises'; 16``` 17 18```cjs 19const readline = require('node:readline/promises'); 20``` 21 22To use the callback and sync APIs: 23 24```mjs 25import * as readline from 'node:readline'; 26``` 27 28```cjs 29const readline = require('node:readline'); 30``` 31 32The following simple example illustrates the basic use of the `node:readline` 33module. 34 35```mjs 36import * as readline from 'node:readline/promises'; 37import { stdin as input, stdout as output } from 'node:process'; 38 39const rl = readline.createInterface({ input, output }); 40 41const answer = await rl.question('What do you think of Node.js? '); 42 43console.log(`Thank you for your valuable feedback: ${answer}`); 44 45rl.close(); 46``` 47 48```cjs 49const readline = require('node:readline'); 50const { stdin: input, stdout: output } = require('node:process'); 51 52const rl = readline.createInterface({ input, output }); 53 54rl.question('What do you think of Node.js? ', (answer) => { 55 // TODO: Log the answer in a database 56 console.log(`Thank you for your valuable feedback: ${answer}`); 57 58 rl.close(); 59}); 60``` 61 62Once this code is invoked, the Node.js application will not terminate until the 63`readline.Interface` is closed because the interface waits for data to be 64received on the `input` stream. 65 66<a id='readline_class_interface'></a> 67 68## Class: `InterfaceConstructor` 69 70<!-- YAML 71added: v0.1.104 72--> 73 74* Extends: {EventEmitter} 75 76Instances of the `InterfaceConstructor` class are constructed using the 77`readlinePromises.createInterface()` or `readline.createInterface()` method. 78Every instance is associated with a single `input` [Readable][] stream and a 79single `output` [Writable][] stream. 80The `output` stream is used to print prompts for user input that arrives on, 81and is read from, the `input` stream. 82 83### Event: `'close'` 84 85<!-- YAML 86added: v0.1.98 87--> 88 89The `'close'` event is emitted when one of the following occur: 90 91* The `rl.close()` method is called and the `InterfaceConstructor` instance has 92 relinquished control over the `input` and `output` streams; 93* The `input` stream receives its `'end'` event; 94* The `input` stream receives <kbd>Ctrl</kbd>+<kbd>D</kbd> to signal 95 end-of-transmission (EOT); 96* The `input` stream receives <kbd>Ctrl</kbd>+<kbd>C</kbd> to signal `SIGINT` 97 and there is no `'SIGINT'` event listener registered on the 98 `InterfaceConstructor` instance. 99 100The listener function is called without passing any arguments. 101 102The `InterfaceConstructor` instance is finished once the `'close'` event is 103emitted. 104 105### Event: `'line'` 106 107<!-- YAML 108added: v0.1.98 109--> 110 111The `'line'` event is emitted whenever the `input` stream receives an 112end-of-line input (`\n`, `\r`, or `\r\n`). This usually occurs when the user 113presses <kbd>Enter</kbd> or <kbd>Return</kbd>. 114 115The `'line'` event is also emitted if new data has been read from a stream and 116that stream ends without a final end-of-line marker. 117 118The listener function is called with a string containing the single line of 119received input. 120 121```js 122rl.on('line', (input) => { 123 console.log(`Received: ${input}`); 124}); 125``` 126 127### Event: `'history'` 128 129<!-- YAML 130added: 131 - v15.8.0 132 - v14.18.0 133--> 134 135The `'history'` event is emitted whenever the history array has changed. 136 137The listener function is called with an array containing the history array. 138It will reflect all changes, added lines and removed lines due to 139`historySize` and `removeHistoryDuplicates`. 140 141The primary purpose is to allow a listener to persist the history. 142It is also possible for the listener to change the history object. This 143could be useful to prevent certain lines to be added to the history, like 144a password. 145 146```js 147rl.on('history', (history) => { 148 console.log(`Received: ${history}`); 149}); 150``` 151 152### Event: `'pause'` 153 154<!-- YAML 155added: v0.7.5 156--> 157 158The `'pause'` event is emitted when one of the following occur: 159 160* The `input` stream is paused. 161* The `input` stream is not paused and receives the `'SIGCONT'` event. (See 162 events [`'SIGTSTP'`][] and [`'SIGCONT'`][].) 163 164The listener function is called without passing any arguments. 165 166```js 167rl.on('pause', () => { 168 console.log('Readline paused.'); 169}); 170``` 171 172### Event: `'resume'` 173 174<!-- YAML 175added: v0.7.5 176--> 177 178The `'resume'` event is emitted whenever the `input` stream is resumed. 179 180The listener function is called without passing any arguments. 181 182```js 183rl.on('resume', () => { 184 console.log('Readline resumed.'); 185}); 186``` 187 188### Event: `'SIGCONT'` 189 190<!-- YAML 191added: v0.7.5 192--> 193 194The `'SIGCONT'` event is emitted when a Node.js process previously moved into 195the background using <kbd>Ctrl</kbd>+<kbd>Z</kbd> (i.e. `SIGTSTP`) is then 196brought back to the foreground using fg(1p). 197 198If the `input` stream was paused _before_ the `SIGTSTP` request, this event will 199not be emitted. 200 201The listener function is invoked without passing any arguments. 202 203```js 204rl.on('SIGCONT', () => { 205 // `prompt` will automatically resume the stream 206 rl.prompt(); 207}); 208``` 209 210The `'SIGCONT'` event is _not_ supported on Windows. 211 212### Event: `'SIGINT'` 213 214<!-- YAML 215added: v0.3.0 216--> 217 218The `'SIGINT'` event is emitted whenever the `input` stream receives 219a <kbd>Ctrl+C</kbd> input, known typically as `SIGINT`. If there are no 220`'SIGINT'` event listeners registered when the `input` stream receives a 221`SIGINT`, the `'pause'` event will be emitted. 222 223The listener function is invoked without passing any arguments. 224 225```js 226rl.on('SIGINT', () => { 227 rl.question('Are you sure you want to exit? ', (answer) => { 228 if (answer.match(/^y(es)?$/i)) rl.pause(); 229 }); 230}); 231``` 232 233### Event: `'SIGTSTP'` 234 235<!-- YAML 236added: v0.7.5 237--> 238 239The `'SIGTSTP'` event is emitted when the `input` stream receives 240a <kbd>Ctrl</kbd>+<kbd>Z</kbd> input, typically known as `SIGTSTP`. If there are 241no `'SIGTSTP'` event listeners registered when the `input` stream receives a 242`SIGTSTP`, the Node.js process will be sent to the background. 243 244When the program is resumed using fg(1p), the `'pause'` and `'SIGCONT'` events 245will be emitted. These can be used to resume the `input` stream. 246 247The `'pause'` and `'SIGCONT'` events will not be emitted if the `input` was 248paused before the process was sent to the background. 249 250The listener function is invoked without passing any arguments. 251 252```js 253rl.on('SIGTSTP', () => { 254 // This will override SIGTSTP and prevent the program from going to the 255 // background. 256 console.log('Caught SIGTSTP.'); 257}); 258``` 259 260The `'SIGTSTP'` event is _not_ supported on Windows. 261 262### `rl.close()` 263 264<!-- YAML 265added: v0.1.98 266--> 267 268The `rl.close()` method closes the `InterfaceConstructor` instance and 269relinquishes control over the `input` and `output` streams. When called, 270the `'close'` event will be emitted. 271 272Calling `rl.close()` does not immediately stop other events (including `'line'`) 273from being emitted by the `InterfaceConstructor` instance. 274 275### `rl.pause()` 276 277<!-- YAML 278added: v0.3.4 279--> 280 281The `rl.pause()` method pauses the `input` stream, allowing it to be resumed 282later if necessary. 283 284Calling `rl.pause()` does not immediately pause other events (including 285`'line'`) from being emitted by the `InterfaceConstructor` instance. 286 287### `rl.prompt([preserveCursor])` 288 289<!-- YAML 290added: v0.1.98 291--> 292 293* `preserveCursor` {boolean} If `true`, prevents the cursor placement from 294 being reset to `0`. 295 296The `rl.prompt()` method writes the `InterfaceConstructor` instances configured 297`prompt` to a new line in `output` in order to provide a user with a new 298location at which to provide input. 299 300When called, `rl.prompt()` will resume the `input` stream if it has been 301paused. 302 303If the `InterfaceConstructor` was created with `output` set to `null` or 304`undefined` the prompt is not written. 305 306### `rl.question(query[, options], callback)` 307 308<!-- YAML 309added: v0.3.3 310--> 311 312* `query` {string} A statement or query to write to `output`, prepended to the 313 prompt. 314* `options` {Object} 315 * `signal` {AbortSignal} Optionally allows the `question()` to be canceled 316 using an `AbortController`. 317* `callback` {Function} A callback function that is invoked with the user's 318 input in response to the `query`. 319 320The `rl.question()` method displays the `query` by writing it to the `output`, 321waits for user input to be provided on `input`, then invokes the `callback` 322function passing the provided input as the first argument. 323 324When called, `rl.question()` will resume the `input` stream if it has been 325paused. 326 327If the `InterfaceConstructor` was created with `output` set to `null` or 328`undefined` the `query` is not written. 329 330The `callback` function passed to `rl.question()` does not follow the typical 331pattern of accepting an `Error` object or `null` as the first argument. 332The `callback` is called with the provided answer as the only argument. 333 334An error will be thrown if calling `rl.question()` after `rl.close()`. 335 336Example usage: 337 338```js 339rl.question('What is your favorite food? ', (answer) => { 340 console.log(`Oh, so your favorite food is ${answer}`); 341}); 342``` 343 344Using an `AbortController` to cancel a question. 345 346```js 347const ac = new AbortController(); 348const signal = ac.signal; 349 350rl.question('What is your favorite food? ', { signal }, (answer) => { 351 console.log(`Oh, so your favorite food is ${answer}`); 352}); 353 354signal.addEventListener('abort', () => { 355 console.log('The food question timed out'); 356}, { once: true }); 357 358setTimeout(() => ac.abort(), 10000); 359``` 360 361### `rl.resume()` 362 363<!-- YAML 364added: v0.3.4 365--> 366 367The `rl.resume()` method resumes the `input` stream if it has been paused. 368 369### `rl.setPrompt(prompt)` 370 371<!-- YAML 372added: v0.1.98 373--> 374 375* `prompt` {string} 376 377The `rl.setPrompt()` method sets the prompt that will be written to `output` 378whenever `rl.prompt()` is called. 379 380### `rl.getPrompt()` 381 382<!-- YAML 383added: 384 - v15.3.0 385 - v14.17.0 386--> 387 388* Returns: {string} the current prompt string 389 390The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. 391 392### `rl.write(data[, key])` 393 394<!-- YAML 395added: v0.1.98 396--> 397 398* `data` {string} 399* `key` {Object} 400 * `ctrl` {boolean} `true` to indicate the <kbd>Ctrl</kbd> key. 401 * `meta` {boolean} `true` to indicate the <kbd>Meta</kbd> key. 402 * `shift` {boolean} `true` to indicate the <kbd>Shift</kbd> key. 403 * `name` {string} The name of the a key. 404 405The `rl.write()` method will write either `data` or a key sequence identified 406by `key` to the `output`. The `key` argument is supported only if `output` is 407a [TTY][] text terminal. See [TTY keybindings][] for a list of key 408combinations. 409 410If `key` is specified, `data` is ignored. 411 412When called, `rl.write()` will resume the `input` stream if it has been 413paused. 414 415If the `InterfaceConstructor` was created with `output` set to `null` or 416`undefined` the `data` and `key` are not written. 417 418```js 419rl.write('Delete this!'); 420// Simulate Ctrl+U to delete the line written previously 421rl.write(null, { ctrl: true, name: 'u' }); 422``` 423 424The `rl.write()` method will write the data to the `readline` `Interface`'s 425`input` _as if it were provided by the user_. 426 427### `rl[Symbol.asyncIterator]()` 428 429<!-- YAML 430added: 431 - v11.4.0 432 - v10.16.0 433changes: 434 - version: 435 - v11.14.0 436 - v10.17.0 437 pr-url: https://github.com/nodejs/node/pull/26989 438 description: Symbol.asyncIterator support is no longer experimental. 439--> 440 441* Returns: {AsyncIterator} 442 443Create an `AsyncIterator` object that iterates through each line in the input 444stream as a string. This method allows asynchronous iteration of 445`InterfaceConstructor` objects through `for await...of` loops. 446 447Errors in the input stream are not forwarded. 448 449If the loop is terminated with `break`, `throw`, or `return`, 450[`rl.close()`][] will be called. In other words, iterating over a 451`InterfaceConstructor` will always consume the input stream fully. 452 453Performance is not on par with the traditional `'line'` event API. Use `'line'` 454instead for performance-sensitive applications. 455 456```js 457async function processLineByLine() { 458 const rl = readline.createInterface({ 459 // ... 460 }); 461 462 for await (const line of rl) { 463 // Each line in the readline input will be successively available here as 464 // `line`. 465 } 466} 467``` 468 469`readline.createInterface()` will start to consume the input stream once 470invoked. Having asynchronous operations between interface creation and 471asynchronous iteration may result in missed lines. 472 473### `rl.line` 474 475<!-- YAML 476added: v0.1.98 477changes: 478 - version: 479 - v15.8.0 480 - v14.18.0 481 pr-url: https://github.com/nodejs/node/pull/33676 482 description: Value will always be a string, never undefined. 483--> 484 485* {string} 486 487The current input data being processed by node. 488 489This can be used when collecting input from a TTY stream to retrieve the 490current value that has been processed thus far, prior to the `line` event 491being emitted. Once the `line` event has been emitted, this property will 492be an empty string. 493 494Be aware that modifying the value during the instance runtime may have 495unintended consequences if `rl.cursor` is not also controlled. 496 497**If not using a TTY stream for input, use the [`'line'`][] event.** 498 499One possible use case would be as follows: 500 501```js 502const values = ['lorem ipsum', 'dolor sit amet']; 503const rl = readline.createInterface(process.stdin); 504const showResults = debounce(() => { 505 console.log( 506 '\n', 507 values.filter((val) => val.startsWith(rl.line)).join(' '), 508 ); 509}, 300); 510process.stdin.on('keypress', (c, k) => { 511 showResults(); 512}); 513``` 514 515### `rl.cursor` 516 517<!-- YAML 518added: v0.1.98 519--> 520 521* {number|undefined} 522 523The cursor position relative to `rl.line`. 524 525This will track where the current cursor lands in the input string, when 526reading input from a TTY stream. The position of cursor determines the 527portion of the input string that will be modified as input is processed, 528as well as the column where the terminal caret will be rendered. 529 530### `rl.getCursorPos()` 531 532<!-- YAML 533added: 534 - v13.5.0 535 - v12.16.0 536--> 537 538* Returns: {Object} 539 * `rows` {number} the row of the prompt the cursor currently lands on 540 * `cols` {number} the screen column the cursor currently lands on 541 542Returns the real position of the cursor in relation to the input 543prompt + string. Long input (wrapping) strings, as well as multiple 544line prompts are included in the calculations. 545 546## Promises API 547 548<!-- YAML 549added: v17.0.0 550--> 551 552> Stability: 1 - Experimental 553 554### Class: `readlinePromises.Interface` 555 556<!-- YAML 557added: v17.0.0 558--> 559 560* Extends: {readline.InterfaceConstructor} 561 562Instances of the `readlinePromises.Interface` class are constructed using the 563`readlinePromises.createInterface()` method. Every instance is associated with a 564single `input` [Readable][] stream and a single `output` [Writable][] stream. 565The `output` stream is used to print prompts for user input that arrives on, 566and is read from, the `input` stream. 567 568#### `rl.question(query[, options])` 569 570<!-- YAML 571added: v17.0.0 572--> 573 574* `query` {string} A statement or query to write to `output`, prepended to the 575 prompt. 576* `options` {Object} 577 * `signal` {AbortSignal} Optionally allows the `question()` to be canceled 578 using an `AbortSignal`. 579* Returns: {Promise} A promise that is fulfilled with the user's 580 input in response to the `query`. 581 582The `rl.question()` method displays the `query` by writing it to the `output`, 583waits for user input to be provided on `input`, then invokes the `callback` 584function passing the provided input as the first argument. 585 586When called, `rl.question()` will resume the `input` stream if it has been 587paused. 588 589If the `readlinePromises.Interface` was created with `output` set to `null` or 590`undefined` the `query` is not written. 591 592If the question is called after `rl.close()`, it returns a rejected promise. 593 594Example usage: 595 596```mjs 597const answer = await rl.question('What is your favorite food? '); 598console.log(`Oh, so your favorite food is ${answer}`); 599``` 600 601Using an `AbortSignal` to cancel a question. 602 603```mjs 604const signal = AbortSignal.timeout(10_000); 605 606signal.addEventListener('abort', () => { 607 console.log('The food question timed out'); 608}, { once: true }); 609 610const answer = await rl.question('What is your favorite food? ', { signal }); 611console.log(`Oh, so your favorite food is ${answer}`); 612``` 613 614### Class: `readlinePromises.Readline` 615 616<!-- YAML 617added: v17.0.0 618--> 619 620#### `new readlinePromises.Readline(stream[, options])` 621 622<!-- YAML 623added: v17.0.0 624--> 625 626* `stream` {stream.Writable} A [TTY][] stream. 627* `options` {Object} 628 * `autoCommit` {boolean} If `true`, no need to call `rl.commit()`. 629 630#### `rl.clearLine(dir)` 631 632<!-- YAML 633added: v17.0.0 634--> 635 636* `dir` {integer} 637 * `-1`: to the left from cursor 638 * `1`: to the right from cursor 639 * `0`: the entire line 640* Returns: this 641 642The `rl.clearLine()` method adds to the internal list of pending action an 643action that clears current line of the associated `stream` in a specified 644direction identified by `dir`. 645Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` 646was passed to the constructor. 647 648#### `rl.clearScreenDown()` 649 650<!-- YAML 651added: v17.0.0 652--> 653 654* Returns: this 655 656The `rl.clearScreenDown()` method adds to the internal list of pending action an 657action that clears the associated stream from the current position of the 658cursor down. 659Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` 660was passed to the constructor. 661 662#### `rl.commit()` 663 664<!-- YAML 665added: v17.0.0 666--> 667 668* Returns: {Promise} 669 670The `rl.commit()` method sends all the pending actions to the associated 671`stream` and clears the internal list of pending actions. 672 673#### `rl.cursorTo(x[, y])` 674 675<!-- YAML 676added: v17.0.0 677--> 678 679* `x` {integer} 680* `y` {integer} 681* Returns: this 682 683The `rl.cursorTo()` method adds to the internal list of pending action an action 684that moves cursor to the specified position in the associated `stream`. 685Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` 686was passed to the constructor. 687 688#### `rl.moveCursor(dx, dy)` 689 690<!-- YAML 691added: v17.0.0 692--> 693 694* `dx` {integer} 695* `dy` {integer} 696* Returns: this 697 698The `rl.moveCursor()` method adds to the internal list of pending action an 699action that moves the cursor _relative_ to its current position in the 700associated `stream`. 701Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` 702was passed to the constructor. 703 704#### `rl.rollback()` 705 706<!-- YAML 707added: v17.0.0 708--> 709 710* Returns: this 711 712The `rl.rollback` methods clears the internal list of pending actions without 713sending it to the associated `stream`. 714 715### `readlinePromises.createInterface(options)` 716 717<!-- YAML 718added: v17.0.0 719--> 720 721* `options` {Object} 722 * `input` {stream.Readable} The [Readable][] stream to listen to. This option 723 is _required_. 724 * `output` {stream.Writable} The [Writable][] stream to write readline data 725 to. 726 * `completer` {Function} An optional function used for Tab autocompletion. 727 * `terminal` {boolean} `true` if the `input` and `output` streams should be 728 treated like a TTY, and have ANSI/VT100 escape codes written to it. 729 **Default:** checking `isTTY` on the `output` stream upon instantiation. 730 * `history` {string\[]} Initial list of history lines. This option makes sense 731 only if `terminal` is set to `true` by the user or by an internal `output` 732 check, otherwise the history caching mechanism is not initialized at all. 733 **Default:** `[]`. 734 * `historySize` {number} Maximum number of history lines retained. To disable 735 the history set this value to `0`. This option makes sense only if 736 `terminal` is set to `true` by the user or by an internal `output` check, 737 otherwise the history caching mechanism is not initialized at all. 738 **Default:** `30`. 739 * `removeHistoryDuplicates` {boolean} If `true`, when a new input line added 740 to the history list duplicates an older one, this removes the older line 741 from the list. **Default:** `false`. 742 * `prompt` {string} The prompt string to use. **Default:** `'> '`. 743 * `crlfDelay` {number} If the delay between `\r` and `\n` exceeds 744 `crlfDelay` milliseconds, both `\r` and `\n` will be treated as separate 745 end-of-line input. `crlfDelay` will be coerced to a number no less than 746 `100`. It can be set to `Infinity`, in which case `\r` followed by `\n` 747 will always be considered a single newline (which may be reasonable for 748 [reading files][] with `\r\n` line delimiter). **Default:** `100`. 749 * `escapeCodeTimeout` {number} The duration `readlinePromises` will wait for a 750 character (when reading an ambiguous key sequence in milliseconds one that 751 can both form a complete key sequence using the input read so far and can 752 take additional input to complete a longer key sequence). 753 **Default:** `500`. 754 * `tabSize` {integer} The number of spaces a tab is equal to (minimum 1). 755 **Default:** `8`. 756* Returns: {readlinePromises.Interface} 757 758The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` 759instance. 760 761```js 762const readlinePromises = require('node:readline/promises'); 763const rl = readlinePromises.createInterface({ 764 input: process.stdin, 765 output: process.stdout, 766}); 767``` 768 769Once the `readlinePromises.Interface` instance is created, the most common case 770is to listen for the `'line'` event: 771 772```js 773rl.on('line', (line) => { 774 console.log(`Received: ${line}`); 775}); 776``` 777 778If `terminal` is `true` for this instance then the `output` stream will get 779the best compatibility if it defines an `output.columns` property and emits 780a `'resize'` event on the `output` if or when the columns ever change 781([`process.stdout`][] does this automatically when it is a TTY). 782 783#### Use of the `completer` function 784 785The `completer` function takes the current line entered by the user 786as an argument, and returns an `Array` with 2 entries: 787 788* An `Array` with matching entries for the completion. 789* The substring that was used for the matching. 790 791For instance: `[[substr1, substr2, ...], originalsubstring]`. 792 793```js 794function completer(line) { 795 const completions = '.help .error .exit .quit .q'.split(' '); 796 const hits = completions.filter((c) => c.startsWith(line)); 797 // Show all completions if none found 798 return [hits.length ? hits : completions, line]; 799} 800``` 801 802The `completer` function can also return a {Promise}, or be asynchronous: 803 804```js 805async function completer(linePartial) { 806 await someAsyncWork(); 807 return [['123'], linePartial]; 808} 809``` 810 811## Callback API 812 813<!-- YAML 814added: v0.1.104 815--> 816 817### Class: `readline.Interface` 818 819<!-- YAML 820added: v0.1.104 821changes: 822 - version: v17.0.0 823 pr-url: https://github.com/nodejs/node/pull/37947 824 description: The class `readline.Interface` now inherits from `Interface`. 825--> 826 827* Extends: {readline.InterfaceConstructor} 828 829Instances of the `readline.Interface` class are constructed using the 830`readline.createInterface()` method. Every instance is associated with a 831single `input` [Readable][] stream and a single `output` [Writable][] stream. 832The `output` stream is used to print prompts for user input that arrives on, 833and is read from, the `input` stream. 834 835#### `rl.question(query[, options], callback)` 836 837<!-- YAML 838added: v0.3.3 839--> 840 841* `query` {string} A statement or query to write to `output`, prepended to the 842 prompt. 843* `options` {Object} 844 * `signal` {AbortSignal} Optionally allows the `question()` to be canceled 845 using an `AbortController`. 846* `callback` {Function} A callback function that is invoked with the user's 847 input in response to the `query`. 848 849The `rl.question()` method displays the `query` by writing it to the `output`, 850waits for user input to be provided on `input`, then invokes the `callback` 851function passing the provided input as the first argument. 852 853When called, `rl.question()` will resume the `input` stream if it has been 854paused. 855 856If the `readline.Interface` was created with `output` set to `null` or 857`undefined` the `query` is not written. 858 859The `callback` function passed to `rl.question()` does not follow the typical 860pattern of accepting an `Error` object or `null` as the first argument. 861The `callback` is called with the provided answer as the only argument. 862 863An error will be thrown if calling `rl.question()` after `rl.close()`. 864 865Example usage: 866 867```js 868rl.question('What is your favorite food? ', (answer) => { 869 console.log(`Oh, so your favorite food is ${answer}`); 870}); 871``` 872 873Using an `AbortController` to cancel a question. 874 875```js 876const ac = new AbortController(); 877const signal = ac.signal; 878 879rl.question('What is your favorite food? ', { signal }, (answer) => { 880 console.log(`Oh, so your favorite food is ${answer}`); 881}); 882 883signal.addEventListener('abort', () => { 884 console.log('The food question timed out'); 885}, { once: true }); 886 887setTimeout(() => ac.abort(), 10000); 888``` 889 890### `readline.clearLine(stream, dir[, callback])` 891 892<!-- YAML 893added: v0.7.7 894changes: 895 - version: v18.0.0 896 pr-url: https://github.com/nodejs/node/pull/41678 897 description: Passing an invalid callback to the `callback` argument 898 now throws `ERR_INVALID_ARG_TYPE` instead of 899 `ERR_INVALID_CALLBACK`. 900 - version: v12.7.0 901 pr-url: https://github.com/nodejs/node/pull/28674 902 description: The stream's write() callback and return value are exposed. 903--> 904 905* `stream` {stream.Writable} 906* `dir` {number} 907 * `-1`: to the left from cursor 908 * `1`: to the right from cursor 909 * `0`: the entire line 910* `callback` {Function} Invoked once the operation completes. 911* Returns: {boolean} `false` if `stream` wishes for the calling code to wait for 912 the `'drain'` event to be emitted before continuing to write additional data; 913 otherwise `true`. 914 915The `readline.clearLine()` method clears current line of given [TTY][] stream 916in a specified direction identified by `dir`. 917 918### `readline.clearScreenDown(stream[, callback])` 919 920<!-- YAML 921added: v0.7.7 922changes: 923 - version: v18.0.0 924 pr-url: https://github.com/nodejs/node/pull/41678 925 description: Passing an invalid callback to the `callback` argument 926 now throws `ERR_INVALID_ARG_TYPE` instead of 927 `ERR_INVALID_CALLBACK`. 928 - version: v12.7.0 929 pr-url: https://github.com/nodejs/node/pull/28641 930 description: The stream's write() callback and return value are exposed. 931--> 932 933* `stream` {stream.Writable} 934* `callback` {Function} Invoked once the operation completes. 935* Returns: {boolean} `false` if `stream` wishes for the calling code to wait for 936 the `'drain'` event to be emitted before continuing to write additional data; 937 otherwise `true`. 938 939The `readline.clearScreenDown()` method clears the given [TTY][] stream from 940the current position of the cursor down. 941 942### `readline.createInterface(options)` 943 944<!-- YAML 945added: v0.1.98 946changes: 947 - version: 948 - v15.14.0 949 - v14.18.0 950 pr-url: https://github.com/nodejs/node/pull/37932 951 description: The `signal` option is supported now. 952 - version: 953 - v15.8.0 954 - v14.18.0 955 pr-url: https://github.com/nodejs/node/pull/33662 956 description: The `history` option is supported now. 957 - version: v13.9.0 958 pr-url: https://github.com/nodejs/node/pull/31318 959 description: The `tabSize` option is supported now. 960 - version: 961 - v8.3.0 962 - v6.11.4 963 pr-url: https://github.com/nodejs/node/pull/13497 964 description: Remove max limit of `crlfDelay` option. 965 - version: v6.6.0 966 pr-url: https://github.com/nodejs/node/pull/8109 967 description: The `crlfDelay` option is supported now. 968 - version: v6.3.0 969 pr-url: https://github.com/nodejs/node/pull/7125 970 description: The `prompt` option is supported now. 971 - version: v6.0.0 972 pr-url: https://github.com/nodejs/node/pull/6352 973 description: The `historySize` option can be `0` now. 974--> 975 976* `options` {Object} 977 * `input` {stream.Readable} The [Readable][] stream to listen to. This option 978 is _required_. 979 * `output` {stream.Writable} The [Writable][] stream to write readline data 980 to. 981 * `completer` {Function} An optional function used for Tab autocompletion. 982 * `terminal` {boolean} `true` if the `input` and `output` streams should be 983 treated like a TTY, and have ANSI/VT100 escape codes written to it. 984 **Default:** checking `isTTY` on the `output` stream upon instantiation. 985 * `history` {string\[]} Initial list of history lines. This option makes sense 986 only if `terminal` is set to `true` by the user or by an internal `output` 987 check, otherwise the history caching mechanism is not initialized at all. 988 **Default:** `[]`. 989 * `historySize` {number} Maximum number of history lines retained. To disable 990 the history set this value to `0`. This option makes sense only if 991 `terminal` is set to `true` by the user or by an internal `output` check, 992 otherwise the history caching mechanism is not initialized at all. 993 **Default:** `30`. 994 * `removeHistoryDuplicates` {boolean} If `true`, when a new input line added 995 to the history list duplicates an older one, this removes the older line 996 from the list. **Default:** `false`. 997 * `prompt` {string} The prompt string to use. **Default:** `'> '`. 998 * `crlfDelay` {number} If the delay between `\r` and `\n` exceeds 999 `crlfDelay` milliseconds, both `\r` and `\n` will be treated as separate 1000 end-of-line input. `crlfDelay` will be coerced to a number no less than 1001 `100`. It can be set to `Infinity`, in which case `\r` followed by `\n` 1002 will always be considered a single newline (which may be reasonable for 1003 [reading files][] with `\r\n` line delimiter). **Default:** `100`. 1004 * `escapeCodeTimeout` {number} The duration `readline` will wait for a 1005 character (when reading an ambiguous key sequence in milliseconds one that 1006 can both form a complete key sequence using the input read so far and can 1007 take additional input to complete a longer key sequence). 1008 **Default:** `500`. 1009 * `tabSize` {integer} The number of spaces a tab is equal to (minimum 1). 1010 **Default:** `8`. 1011 * `signal` {AbortSignal} Allows closing the interface using an AbortSignal. 1012 Aborting the signal will internally call `close` on the interface. 1013* Returns: {readline.Interface} 1014 1015The `readline.createInterface()` method creates a new `readline.Interface` 1016instance. 1017 1018```js 1019const readline = require('node:readline'); 1020const rl = readline.createInterface({ 1021 input: process.stdin, 1022 output: process.stdout, 1023}); 1024``` 1025 1026Once the `readline.Interface` instance is created, the most common case is to 1027listen for the `'line'` event: 1028 1029```js 1030rl.on('line', (line) => { 1031 console.log(`Received: ${line}`); 1032}); 1033``` 1034 1035If `terminal` is `true` for this instance then the `output` stream will get 1036the best compatibility if it defines an `output.columns` property and emits 1037a `'resize'` event on the `output` if or when the columns ever change 1038([`process.stdout`][] does this automatically when it is a TTY). 1039 1040When creating a `readline.Interface` using `stdin` as input, the program 1041will not terminate until it receives an [EOF character][]. To exit without 1042waiting for user input, call `process.stdin.unref()`. 1043 1044#### Use of the `completer` function 1045 1046The `completer` function takes the current line entered by the user 1047as an argument, and returns an `Array` with 2 entries: 1048 1049* An `Array` with matching entries for the completion. 1050* The substring that was used for the matching. 1051 1052For instance: `[[substr1, substr2, ...], originalsubstring]`. 1053 1054```js 1055function completer(line) { 1056 const completions = '.help .error .exit .quit .q'.split(' '); 1057 const hits = completions.filter((c) => c.startsWith(line)); 1058 // Show all completions if none found 1059 return [hits.length ? hits : completions, line]; 1060} 1061``` 1062 1063The `completer` function can be called asynchronously if it accepts two 1064arguments: 1065 1066```js 1067function completer(linePartial, callback) { 1068 callback(null, [['123'], linePartial]); 1069} 1070``` 1071 1072### `readline.cursorTo(stream, x[, y][, callback])` 1073 1074<!-- YAML 1075added: v0.7.7 1076changes: 1077 - version: v18.0.0 1078 pr-url: https://github.com/nodejs/node/pull/41678 1079 description: Passing an invalid callback to the `callback` argument 1080 now throws `ERR_INVALID_ARG_TYPE` instead of 1081 `ERR_INVALID_CALLBACK`. 1082 - version: v12.7.0 1083 pr-url: https://github.com/nodejs/node/pull/28674 1084 description: The stream's write() callback and return value are exposed. 1085--> 1086 1087* `stream` {stream.Writable} 1088* `x` {number} 1089* `y` {number} 1090* `callback` {Function} Invoked once the operation completes. 1091* Returns: {boolean} `false` if `stream` wishes for the calling code to wait for 1092 the `'drain'` event to be emitted before continuing to write additional data; 1093 otherwise `true`. 1094 1095The `readline.cursorTo()` method moves cursor to the specified position in a 1096given [TTY][] `stream`. 1097 1098### `readline.moveCursor(stream, dx, dy[, callback])` 1099 1100<!-- YAML 1101added: v0.7.7 1102changes: 1103 - version: v18.0.0 1104 pr-url: https://github.com/nodejs/node/pull/41678 1105 description: Passing an invalid callback to the `callback` argument 1106 now throws `ERR_INVALID_ARG_TYPE` instead of 1107 `ERR_INVALID_CALLBACK`. 1108 - version: v12.7.0 1109 pr-url: https://github.com/nodejs/node/pull/28674 1110 description: The stream's write() callback and return value are exposed. 1111--> 1112 1113* `stream` {stream.Writable} 1114* `dx` {number} 1115* `dy` {number} 1116* `callback` {Function} Invoked once the operation completes. 1117* Returns: {boolean} `false` if `stream` wishes for the calling code to wait for 1118 the `'drain'` event to be emitted before continuing to write additional data; 1119 otherwise `true`. 1120 1121The `readline.moveCursor()` method moves the cursor _relative_ to its current 1122position in a given [TTY][] `stream`. 1123 1124## `readline.emitKeypressEvents(stream[, interface])` 1125 1126<!-- YAML 1127added: v0.7.7 1128--> 1129 1130* `stream` {stream.Readable} 1131* `interface` {readline.InterfaceConstructor} 1132 1133The `readline.emitKeypressEvents()` method causes the given [Readable][] 1134stream to begin emitting `'keypress'` events corresponding to received input. 1135 1136Optionally, `interface` specifies a `readline.Interface` instance for which 1137autocompletion is disabled when copy-pasted input is detected. 1138 1139If the `stream` is a [TTY][], then it must be in raw mode. 1140 1141This is automatically called by any readline instance on its `input` if the 1142`input` is a terminal. Closing the `readline` instance does not stop 1143the `input` from emitting `'keypress'` events. 1144 1145```js 1146readline.emitKeypressEvents(process.stdin); 1147if (process.stdin.isTTY) 1148 process.stdin.setRawMode(true); 1149``` 1150 1151## Example: Tiny CLI 1152 1153The following example illustrates the use of `readline.Interface` class to 1154implement a small command-line interface: 1155 1156```js 1157const readline = require('node:readline'); 1158const rl = readline.createInterface({ 1159 input: process.stdin, 1160 output: process.stdout, 1161 prompt: 'OHAI> ', 1162}); 1163 1164rl.prompt(); 1165 1166rl.on('line', (line) => { 1167 switch (line.trim()) { 1168 case 'hello': 1169 console.log('world!'); 1170 break; 1171 default: 1172 console.log(`Say what? I might have heard '${line.trim()}'`); 1173 break; 1174 } 1175 rl.prompt(); 1176}).on('close', () => { 1177 console.log('Have a great day!'); 1178 process.exit(0); 1179}); 1180``` 1181 1182## Example: Read file stream line-by-Line 1183 1184A common use case for `readline` is to consume an input file one line at a 1185time. The easiest way to do so is leveraging the [`fs.ReadStream`][] API as 1186well as a `for await...of` loop: 1187 1188```js 1189const fs = require('node:fs'); 1190const readline = require('node:readline'); 1191 1192async function processLineByLine() { 1193 const fileStream = fs.createReadStream('input.txt'); 1194 1195 const rl = readline.createInterface({ 1196 input: fileStream, 1197 crlfDelay: Infinity, 1198 }); 1199 // Note: we use the crlfDelay option to recognize all instances of CR LF 1200 // ('\r\n') in input.txt as a single line break. 1201 1202 for await (const line of rl) { 1203 // Each line in input.txt will be successively available here as `line`. 1204 console.log(`Line from file: ${line}`); 1205 } 1206} 1207 1208processLineByLine(); 1209``` 1210 1211Alternatively, one could use the [`'line'`][] event: 1212 1213```js 1214const fs = require('node:fs'); 1215const readline = require('node:readline'); 1216 1217const rl = readline.createInterface({ 1218 input: fs.createReadStream('sample.txt'), 1219 crlfDelay: Infinity, 1220}); 1221 1222rl.on('line', (line) => { 1223 console.log(`Line from file: ${line}`); 1224}); 1225``` 1226 1227Currently, `for await...of` loop can be a bit slower. If `async` / `await` 1228flow and speed are both essential, a mixed approach can be applied: 1229 1230```js 1231const { once } = require('node:events'); 1232const { createReadStream } = require('node:fs'); 1233const { createInterface } = require('node:readline'); 1234 1235(async function processLineByLine() { 1236 try { 1237 const rl = createInterface({ 1238 input: createReadStream('big-file.txt'), 1239 crlfDelay: Infinity, 1240 }); 1241 1242 rl.on('line', (line) => { 1243 // Process the line. 1244 }); 1245 1246 await once(rl, 'close'); 1247 1248 console.log('File processed.'); 1249 } catch (err) { 1250 console.error(err); 1251 } 1252})(); 1253``` 1254 1255## TTY keybindings 1256 1257<table> 1258 <tr> 1259 <th>Keybindings</th> 1260 <th>Description</th> 1261 <th>Notes</th> 1262 </tr> 1263 <tr> 1264 <td><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Backspace</kbd></td> 1265 <td>Delete line left</td> 1266 <td>Doesn't work on Linux, Mac and Windows</td> 1267 </tr> 1268 <tr> 1269 <td><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Delete</kbd></td> 1270 <td>Delete line right</td> 1271 <td>Doesn't work on Mac</td> 1272 </tr> 1273 <tr> 1274 <td><kbd>Ctrl</kbd>+<kbd>C</kbd></td> 1275 <td>Emit <code>SIGINT</code> or close the readline instance</td> 1276 <td></td> 1277 </tr> 1278 <tr> 1279 <td><kbd>Ctrl</kbd>+<kbd>H</kbd></td> 1280 <td>Delete left</td> 1281 <td></td> 1282 </tr> 1283 <tr> 1284 <td><kbd>Ctrl</kbd>+<kbd>D</kbd></td> 1285 <td>Delete right or close the readline instance in case the current line is empty / EOF</td> 1286 <td>Doesn't work on Windows</td> 1287 </tr> 1288 <tr> 1289 <td><kbd>Ctrl</kbd>+<kbd>U</kbd></td> 1290 <td>Delete from the current position to the line start</td> 1291 <td></td> 1292 </tr> 1293 <tr> 1294 <td><kbd>Ctrl</kbd>+<kbd>K</kbd></td> 1295 <td>Delete from the current position to the end of line</td> 1296 <td></td> 1297 </tr> 1298 <tr> 1299 <td><kbd>Ctrl</kbd>+<kbd>Y</kbd></td> 1300 <td>Yank (Recall) the previously deleted text</td> 1301 <td>Only works with text deleted by <kbd>Ctrl</kbd>+<kbd>U</kbd> or <kbd>Ctrl</kbd>+<kbd>K</kbd></td> 1302 </tr> 1303 <tr> 1304 <td><kbd>Meta</kbd>+<kbd>Y</kbd></td> 1305 <td>Cycle among previously deleted lines</td> 1306 <td>Only available when the last keystroke is <kbd>Ctrl</kbd>+<kbd>Y</kbd></td> 1307 </tr> 1308 <tr> 1309 <td><kbd>Ctrl</kbd>+<kbd>A</kbd></td> 1310 <td>Go to start of line</td> 1311 <td></td> 1312 </tr> 1313 <tr> 1314 <td><kbd>Ctrl</kbd>+<kbd>E</kbd></td> 1315 <td>Go to end of line</td> 1316 <td></td> 1317 </tr> 1318 <tr> 1319 <td><kbd>Ctrl</kbd>+<kbd>B</kbd></td> 1320 <td>Back one character</td> 1321 <td></td> 1322 </tr> 1323 <tr> 1324 <td><kbd>Ctrl</kbd>+<kbd>F</kbd></td> 1325 <td>Forward one character</td> 1326 <td></td> 1327 </tr> 1328 <tr> 1329 <td><kbd>Ctrl</kbd>+<kbd>L</kbd></td> 1330 <td>Clear screen</td> 1331 <td></td> 1332 </tr> 1333 <tr> 1334 <td><kbd>Ctrl</kbd>+<kbd>N</kbd></td> 1335 <td>Next history item</td> 1336 <td></td> 1337 </tr> 1338 <tr> 1339 <td><kbd>Ctrl</kbd>+<kbd>P</kbd></td> 1340 <td>Previous history item</td> 1341 <td></td> 1342 </tr> 1343 <tr> 1344 <td><kbd>Ctrl</kbd>+<kbd>-</kbd></td> 1345 <td>Undo previous change</td> 1346 <td>Any keystroke that emits key code <code>0x1F</code> will do this action. 1347 In many terminals, for example <code>xterm</code>, 1348 this is bound to <kbd>Ctrl</kbd>+<kbd>-</kbd>.</td> 1349 </tr> 1350 <tr> 1351 <td><kbd>Ctrl</kbd>+<kbd>6</kbd></td> 1352 <td>Redo previous change</td> 1353 <td>Many terminals don't have a default redo keystroke. 1354 We choose key code <code>0x1E</code> to perform redo. 1355 In <code>xterm</code>, it is bound to <kbd>Ctrl</kbd>+<kbd>6</kbd> 1356 by default.</td> 1357 </tr> 1358 <tr> 1359 <td><kbd>Ctrl</kbd>+<kbd>Z</kbd></td> 1360 <td>Moves running process into background. Type 1361 <code>fg</code> and press <kbd>Enter</kbd> 1362 to return.</td> 1363 <td>Doesn't work on Windows</td> 1364 </tr> 1365 <tr> 1366 <td><kbd>Ctrl</kbd>+<kbd>W</kbd> or <kbd>Ctrl</kbd> 1367 +<kbd>Backspace</kbd></td> 1368 <td>Delete backward to a word boundary</td> 1369 <td><kbd>Ctrl</kbd>+<kbd>Backspace</kbd> Doesn't 1370 work on Linux, Mac and Windows</td> 1371 </tr> 1372 <tr> 1373 <td><kbd>Ctrl</kbd>+<kbd>Delete</kbd></td> 1374 <td>Delete forward to a word boundary</td> 1375 <td>Doesn't work on Mac</td> 1376 </tr> 1377 <tr> 1378 <td><kbd>Ctrl</kbd>+<kbd>Left arrow</kbd> or 1379 <kbd>Meta</kbd>+<kbd>B</kbd></td> 1380 <td>Word left</td> 1381 <td><kbd>Ctrl</kbd>+<kbd>Left arrow</kbd> Doesn't work 1382 on Mac</td> 1383 </tr> 1384 <tr> 1385 <td><kbd>Ctrl</kbd>+<kbd>Right arrow</kbd> or 1386 <kbd>Meta</kbd>+<kbd>F</kbd></td> 1387 <td>Word right</td> 1388 <td><kbd>Ctrl</kbd>+<kbd>Right arrow</kbd> Doesn't work 1389 on Mac</td> 1390 </tr> 1391 <tr> 1392 <td><kbd>Meta</kbd>+<kbd>D</kbd> or <kbd>Meta</kbd> 1393 +<kbd>Delete</kbd></td> 1394 <td>Delete word right</td> 1395 <td><kbd>Meta</kbd>+<kbd>Delete</kbd> Doesn't work 1396 on windows</td> 1397 </tr> 1398 <tr> 1399 <td><kbd>Meta</kbd>+<kbd>Backspace</kbd></td> 1400 <td>Delete word left</td> 1401 <td>Doesn't work on Mac</td> 1402 </tr> 1403</table> 1404 1405[EOF character]: https://en.wikipedia.org/wiki/End-of-file#EOF_character 1406[Readable]: stream.md#readable-streams 1407[TTY]: tty.md 1408[TTY keybindings]: #tty-keybindings 1409[Writable]: stream.md#writable-streams 1410[`'SIGCONT'`]: #event-sigcont 1411[`'SIGTSTP'`]: #event-sigtstp 1412[`'line'`]: #event-line 1413[`fs.ReadStream`]: fs.md#class-fsreadstream 1414[`process.stdin`]: process.md#processstdin 1415[`process.stdout`]: process.md#processstdout 1416[`rl.close()`]: #rlclose 1417[reading files]: #example-read-file-stream-line-by-line 1418