{ "type": "module", "source": "doc/api/readline.md", "modules": [ { "textRaw": "Readline", "name": "readline", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

The readline module provides an interface for reading data from a Readable\nstream (such as process.stdin) one line at a time. It can be accessed using:

\n
const readline = require('readline');\n
\n

The following simple example illustrates the basic use of the readline module.

\n
const readline = require('readline');\n\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});\n\nrl.question('What do you think of Node.js? ', (answer) => {\n  // TODO: Log the answer in a database\n  console.log(`Thank you for your valuable feedback: ${answer}`);\n\n  rl.close();\n});\n
\n

Once this code is invoked, the Node.js application will not terminate until the\nreadline.Interface is closed because the interface waits for data to be\nreceived on the input stream.

", "classes": [ { "textRaw": "Class: Interface", "type": "class", "name": "Interface", "meta": { "added": [ "v0.1.104" ], "changes": [] }, "desc": "

Instances of the readline.Interface class are constructed using the\nreadline.createInterface() method. Every instance is associated with a\nsingle input Readable stream and a single output Writable stream.\nThe output stream is used to print prompts for user input that arrives on,\nand is read from, the input stream.

", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.1.98" ], "changes": [] }, "params": [], "desc": "

The 'close' event is emitted when one of the following occur:

\n\n

The listener function is called without passing any arguments.

\n

The readline.Interface instance is finished once the 'close' event is\nemitted.

" }, { "textRaw": "Event: 'line'", "type": "event", "name": "line", "meta": { "added": [ "v0.1.98" ], "changes": [] }, "params": [], "desc": "

The 'line' event is emitted whenever the input stream receives an\nend-of-line input (\\n, \\r, or \\r\\n). This usually occurs when the user\npresses the <Enter>, or <Return> keys.

\n

The listener function is called with a string containing the single line of\nreceived input.

\n
rl.on('line', (input) => {\n  console.log(`Received: ${input}`);\n});\n
" }, { "textRaw": "Event: 'pause'", "type": "event", "name": "pause", "meta": { "added": [ "v0.7.5" ], "changes": [] }, "params": [], "desc": "

The 'pause' event is emitted when one of the following occur:

\n\n

The listener function is called without passing any arguments.

\n
rl.on('pause', () => {\n  console.log('Readline paused.');\n});\n
" }, { "textRaw": "Event: 'resume'", "type": "event", "name": "resume", "meta": { "added": [ "v0.7.5" ], "changes": [] }, "params": [], "desc": "

The 'resume' event is emitted whenever the input stream is resumed.

\n

The listener function is called without passing any arguments.

\n
rl.on('resume', () => {\n  console.log('Readline resumed.');\n});\n
" }, { "textRaw": "Event: 'SIGCONT'", "type": "event", "name": "SIGCONT", "meta": { "added": [ "v0.7.5" ], "changes": [] }, "params": [], "desc": "

The 'SIGCONT' event is emitted when a Node.js process previously moved into\nthe background using <ctrl>-Z (i.e. SIGTSTP) is then brought back to the\nforeground using fg(1p).

\n

If the input stream was paused before the SIGTSTP request, this event will\nnot be emitted.

\n

The listener function is invoked without passing any arguments.

\n
rl.on('SIGCONT', () => {\n  // `prompt` will automatically resume the stream\n  rl.prompt();\n});\n
\n

The 'SIGCONT' event is not supported on Windows.

" }, { "textRaw": "Event: 'SIGINT'", "type": "event", "name": "SIGINT", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "params": [], "desc": "

The 'SIGINT' event is emitted whenever the input stream receives a\n<ctrl>-C input, known typically as SIGINT. If there are no 'SIGINT' event\nlisteners registered when the input stream receives a SIGINT, the 'pause'\nevent will be emitted.

\n

The listener function is invoked without passing any arguments.

\n
rl.on('SIGINT', () => {\n  rl.question('Are you sure you want to exit? ', (answer) => {\n    if (answer.match(/^y(es)?$/i)) rl.pause();\n  });\n});\n
" }, { "textRaw": "Event: 'SIGTSTP'", "type": "event", "name": "SIGTSTP", "meta": { "added": [ "v0.7.5" ], "changes": [] }, "params": [], "desc": "

The 'SIGTSTP' event is emitted when the input stream receives a <ctrl>-Z\ninput, typically known as SIGTSTP. If there are no 'SIGTSTP' event listeners\nregistered when the input stream receives a SIGTSTP, the Node.js process\nwill be sent to the background.

\n

When the program is resumed using fg(1p), the 'pause' and 'SIGCONT' events\nwill be emitted. These can be used to resume the input stream.

\n

The 'pause' and 'SIGCONT' events will not be emitted if the input was\npaused before the process was sent to the background.

\n

The listener function is invoked without passing any arguments.

\n
rl.on('SIGTSTP', () => {\n  // This will override SIGTSTP and prevent the program from going to the\n  // background.\n  console.log('Caught SIGTSTP.');\n});\n
\n

The 'SIGTSTP' event is not supported on Windows.

" } ], "methods": [ { "textRaw": "rl.close()", "type": "method", "name": "close", "meta": { "added": [ "v0.1.98" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

The rl.close() method closes the readline.Interface instance and\nrelinquishes control over the input and output streams. When called,\nthe 'close' event will be emitted.

\n

Calling rl.close() does not immediately stop other events (including 'line')\nfrom being emitted by the readline.Interface instance.

" }, { "textRaw": "rl.pause()", "type": "method", "name": "pause", "meta": { "added": [ "v0.3.4" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

The rl.pause() method pauses the input stream, allowing it to be resumed\nlater if necessary.

\n

Calling rl.pause() does not immediately pause other events (including\n'line') from being emitted by the readline.Interface instance.

" }, { "textRaw": "rl.prompt([preserveCursor])", "type": "method", "name": "prompt", "meta": { "added": [ "v0.1.98" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`preserveCursor` {boolean} If `true`, prevents the cursor placement from being reset to `0`.", "name": "preserveCursor", "type": "boolean", "desc": "If `true`, prevents the cursor placement from being reset to `0`.", "optional": true } ] } ], "desc": "

The rl.prompt() method writes the readline.Interface instances configured\nprompt to a new line in output in order to provide a user with a new\nlocation at which to provide input.

\n

When called, rl.prompt() will resume the input stream if it has been\npaused.

\n

If the readline.Interface was created with output set to null or\nundefined the prompt is not written.

" }, { "textRaw": "rl.question(query, callback)", "type": "method", "name": "question", "meta": { "added": [ "v0.3.3" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`query` {string} A statement or query to write to `output`, prepended to the prompt.", "name": "query", "type": "string", "desc": "A statement or query to write to `output`, prepended to the prompt." }, { "textRaw": "`callback` {Function} A callback function that is invoked with the user's input in response to the `query`.", "name": "callback", "type": "Function", "desc": "A callback function that is invoked with the user's input in response to the `query`." } ] } ], "desc": "

The rl.question() method displays the query by writing it to the output,\nwaits for user input to be provided on input, then invokes the callback\nfunction passing the provided input as the first argument.

\n

When called, rl.question() will resume the input stream if it has been\npaused.

\n

If the readline.Interface was created with output set to null or\nundefined the query is not written.

\n

Example usage:

\n
rl.question('What is your favorite food? ', (answer) => {\n  console.log(`Oh, so your favorite food is ${answer}`);\n});\n
\n

The callback function passed to rl.question() does not follow the typical\npattern of accepting an Error object or null as the first argument.\nThe callback is called with the provided answer as the only argument.

" }, { "textRaw": "rl.resume()", "type": "method", "name": "resume", "meta": { "added": [ "v0.3.4" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

The rl.resume() method resumes the input stream if it has been paused.

" }, { "textRaw": "rl.setPrompt(prompt)", "type": "method", "name": "setPrompt", "meta": { "added": [ "v0.1.98" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`prompt` {string}", "name": "prompt", "type": "string" } ] } ], "desc": "

The rl.setPrompt() method sets the prompt that will be written to output\nwhenever rl.prompt() is called.

" }, { "textRaw": "rl.write(data[, key])", "type": "method", "name": "write", "meta": { "added": [ "v0.1.98" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`data` {string}", "name": "data", "type": "string" }, { "textRaw": "`key` {Object}", "name": "key", "type": "Object", "options": [ { "textRaw": "`ctrl` {boolean} `true` to indicate the `` key.", "name": "ctrl", "type": "boolean", "desc": "`true` to indicate the `` key." }, { "textRaw": "`meta` {boolean} `true` to indicate the `` key.", "name": "meta", "type": "boolean", "desc": "`true` to indicate the `` key." }, { "textRaw": "`shift` {boolean} `true` to indicate the `` key.", "name": "shift", "type": "boolean", "desc": "`true` to indicate the `` key." }, { "textRaw": "`name` {string} The name of the a key.", "name": "name", "type": "string", "desc": "The name of the a key." } ], "optional": true } ] } ], "desc": "

The rl.write() method will write either data or a key sequence identified\nby key to the output. The key argument is supported only if output is\na TTY text terminal.

\n

If key is specified, data is ignored.

\n

When called, rl.write() will resume the input stream if it has been\npaused.

\n

If the readline.Interface was created with output set to null or\nundefined the data and key are not written.

\n
rl.write('Delete this!');\n// Simulate Ctrl+u to delete the line written previously\nrl.write(null, { ctrl: true, name: 'u' });\n
\n

The rl.write() method will write the data to the readline Interface's\ninput as if it were provided by the user.

" }, { "textRaw": "rl[Symbol.asyncIterator]()", "type": "method", "name": "[Symbol.asyncIterator]", "meta": { "added": [ "v11.4.0" ], "changes": [ { "version": "v10.17.0", "pr-url": "https://github.com/nodejs/node/pull/26989", "description": "Symbol.asyncIterator support is no longer experimental." } ] }, "stability": 2, "stabilityText": "Stable", "signatures": [ { "return": { "textRaw": "Returns: {AsyncIterator}", "name": "return", "type": "AsyncIterator" }, "params": [] } ], "desc": "

Create an AsyncIterator object that iterates through each line in the input\nstream as a string. This method allows asynchronous iteration of\nreadline.Interface objects through for-await-of loops.

\n

Errors in the input stream are not forwarded.

\n

If the loop is terminated with break, throw, or return,\nrl.close() will be called. In other words, iterating over a\nreadline.Interface will always consume the input stream fully.

\n

A caveat with using this experimental API is that the performance is\ncurrently not on par with the traditional 'line' event API, and thus it is\nnot recommended for performance-sensitive applications. We expect this\nsituation to improve in the future.

\n
async function processLineByLine() {\n  const rl = readline.createInterface({\n    // ...\n  });\n\n  for await (const line of rl) {\n    // Each line in the readline input will be successively available here as\n    // `line`.\n  }\n}\n
" } ] } ], "methods": [ { "textRaw": "readline.clearLine(stream, dir)", "type": "method", "name": "clearLine", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`stream` {stream.Writable}", "name": "stream", "type": "stream.Writable" }, { "textRaw": "`dir` {number}", "name": "dir", "type": "number", "options": [ { "textRaw": "`-1` - to the left from cursor", "name": "-1", "desc": "to the left from cursor" }, { "textRaw": "`1` - to the right from cursor", "name": "1", "desc": "to the right from cursor" }, { "textRaw": "`0` - the entire line", "name": "0", "desc": "the entire line" } ] } ] } ], "desc": "

The readline.clearLine() method clears current line of given TTY stream\nin a specified direction identified by dir.

" }, { "textRaw": "readline.clearScreenDown(stream)", "type": "method", "name": "clearScreenDown", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`stream` {stream.Writable}", "name": "stream", "type": "stream.Writable" } ] } ], "desc": "

The readline.clearScreenDown() method clears the given TTY stream from\nthe current position of the cursor down.

" }, { "textRaw": "readline.createInterface(options)", "type": "method", "name": "createInterface", "meta": { "added": [ "v0.1.98" ], "changes": [ { "version": "v8.3.0, 6.11.4", "pr-url": "https://github.com/nodejs/node/pull/13497", "description": "Remove max limit of `crlfDelay` option." }, { "version": "v6.6.0", "pr-url": "https://github.com/nodejs/node/pull/8109", "description": "The `crlfDelay` option is supported now." }, { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/7125", "description": "The `prompt` option is supported now." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/6352", "description": "The `historySize` option can be `0` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`input` {stream.Readable} The [Readable][] stream to listen to. This option is *required*.", "name": "input", "type": "stream.Readable", "desc": "The [Readable][] stream to listen to. This option is *required*." }, { "textRaw": "`output` {stream.Writable} The [Writable][] stream to write readline data to.", "name": "output", "type": "stream.Writable", "desc": "The [Writable][] stream to write readline data to." }, { "textRaw": "`completer` {Function} An optional function used for Tab autocompletion.", "name": "completer", "type": "Function", "desc": "An optional function used for Tab autocompletion." }, { "textRaw": "`terminal` {boolean} `true` if the `input` and `output` streams should be treated like a TTY, and have ANSI/VT100 escape codes written to it. **Default:** checking `isTTY` on the `output` stream upon instantiation.", "name": "terminal", "type": "boolean", "default": "checking `isTTY` on the `output` stream upon instantiation", "desc": "`true` if the `input` and `output` streams should be treated like a TTY, and have ANSI/VT100 escape codes written to it." }, { "textRaw": "`historySize` {number} Maximum number of history lines retained. To disable the history set this value to `0`. This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, otherwise the history caching mechanism is not initialized at all. **Default:** `30`.", "name": "historySize", "type": "number", "default": "`30`", "desc": "Maximum number of history lines retained. To disable the history set this value to `0`. This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, otherwise the history caching mechanism is not initialized at all." }, { "textRaw": "`prompt` {string} The prompt string to use. **Default:** `'> '`.", "name": "prompt", "type": "string", "default": "`'> '`", "desc": "The prompt string to use." }, { "textRaw": "`crlfDelay` {number} If the delay between `\\r` and `\\n` exceeds `crlfDelay` milliseconds, both `\\r` and `\\n` will be treated as separate end-of-line input. `crlfDelay` will be coerced to a number no less than `100`. It can be set to `Infinity`, in which case `\\r` followed by `\\n` will always be considered a single newline (which may be reasonable for [reading files][] with `\\r\\n` line delimiter). **Default:** `100`.", "name": "crlfDelay", "type": "number", "default": "`100`", "desc": "If the delay between `\\r` and `\\n` exceeds `crlfDelay` milliseconds, both `\\r` and `\\n` will be treated as separate end-of-line input. `crlfDelay` will be coerced to a number no less than `100`. It can be set to `Infinity`, in which case `\\r` followed by `\\n` will always be considered a single newline (which may be reasonable for [reading files][] with `\\r\\n` line delimiter)." }, { "textRaw": "`removeHistoryDuplicates` {boolean} If `true`, when a new input line added to the history list duplicates an older one, this removes the older line from the list. **Default:** `false`.", "name": "removeHistoryDuplicates", "type": "boolean", "default": "`false`", "desc": "If `true`, when a new input line added to the history list duplicates an older one, this removes the older line from the list." }, { "textRaw": "`escapeCodeTimeout` {number} The duration `readline` will wait for a character (when reading an ambiguous key sequence in milliseconds one that can both form a complete key sequence using the input read so far and can take additional input to complete a longer key sequence). **Default:** `500`.", "name": "escapeCodeTimeout", "type": "number", "default": "`500`", "desc": "The duration `readline` will wait for a character (when reading an ambiguous key sequence in milliseconds one that can both form a complete key sequence using the input read so far and can take additional input to complete a longer key sequence)." } ] } ] } ], "desc": "

The readline.createInterface() method creates a new readline.Interface\ninstance.

\n
const readline = require('readline');\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});\n
\n

Once the readline.Interface instance is created, the most common case is to\nlisten for the 'line' event:

\n
rl.on('line', (line) => {\n  console.log(`Received: ${line}`);\n});\n
\n

If terminal is true for this instance then the output stream will get\nthe best compatibility if it defines an output.columns property and emits\na 'resize' event on the output if or when the columns ever change\n(process.stdout does this automatically when it is a TTY).

", "modules": [ { "textRaw": "Use of the `completer` Function", "name": "use_of_the_`completer`_function", "desc": "

The completer function takes the current line entered by the user\nas an argument, and returns an Array with 2 entries:

\n
    \n
  • An Array with matching entries for the completion.
  • \n
  • The substring that was used for the matching.
  • \n
\n

For instance: [[substr1, substr2, ...], originalsubstring].

\n
function completer(line) {\n  const completions = '.help .error .exit .quit .q'.split(' ');\n  const hits = completions.filter((c) => c.startsWith(line));\n  // show all completions if none found\n  return [hits.length ? hits : completions, line];\n}\n
\n

The completer function can be called asynchronously if it accepts two\narguments:

\n
function completer(linePartial, callback) {\n  callback(null, [['123'], linePartial]);\n}\n
", "type": "module", "displayName": "Use of the `completer` Function" } ] }, { "textRaw": "readline.cursorTo(stream, x, y)", "type": "method", "name": "cursorTo", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`stream` {stream.Writable}", "name": "stream", "type": "stream.Writable" }, { "textRaw": "`x` {number}", "name": "x", "type": "number" }, { "textRaw": "`y` {number}", "name": "y", "type": "number" } ] } ], "desc": "

The readline.cursorTo() method moves cursor to the specified position in a\ngiven TTY stream.

" }, { "textRaw": "readline.emitKeypressEvents(stream[, interface])", "type": "method", "name": "emitKeypressEvents", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`stream` {stream.Readable}", "name": "stream", "type": "stream.Readable" }, { "textRaw": "`interface` {readline.Interface}", "name": "interface", "type": "readline.Interface", "optional": true } ] } ], "desc": "

The readline.emitKeypressEvents() method causes the given Readable\nstream to begin emitting 'keypress' events corresponding to received input.

\n

Optionally, interface specifies a readline.Interface instance for which\nautocompletion is disabled when copy-pasted input is detected.

\n

If the stream is a TTY, then it must be in raw mode.

\n

This is automatically called by any readline instance on its input if the\ninput is a terminal. Closing the readline instance does not stop\nthe input from emitting 'keypress' events.

\n
readline.emitKeypressEvents(process.stdin);\nif (process.stdin.isTTY)\n  process.stdin.setRawMode(true);\n
" }, { "textRaw": "readline.moveCursor(stream, dx, dy)", "type": "method", "name": "moveCursor", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`stream` {stream.Writable}", "name": "stream", "type": "stream.Writable" }, { "textRaw": "`dx` {number}", "name": "dx", "type": "number" }, { "textRaw": "`dy` {number}", "name": "dy", "type": "number" } ] } ], "desc": "

The readline.moveCursor() method moves the cursor relative to its current\nposition in a given TTY stream.

\n

Example: Tiny CLI

\n

The following example illustrates the use of readline.Interface class to\nimplement a small command-line interface:

\n
const readline = require('readline');\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout,\n  prompt: 'OHAI> '\n});\n\nrl.prompt();\n\nrl.on('line', (line) => {\n  switch (line.trim()) {\n    case 'hello':\n      console.log('world!');\n      break;\n    default:\n      console.log(`Say what? I might have heard '${line.trim()}'`);\n      break;\n  }\n  rl.prompt();\n}).on('close', () => {\n  console.log('Have a great day!');\n  process.exit(0);\n});\n
\n

Example: Read File Stream Line-by-Line

\n

A common use case for readline is to consume an input file one line at a\ntime. The easiest way to do so is leveraging the fs.ReadStream API as\nwell as a for-await-of loop:

\n
const fs = require('fs');\nconst readline = require('readline');\n\nasync function processLineByLine() {\n  const fileStream = fs.createReadStream('input.txt');\n\n  const rl = readline.createInterface({\n    input: fileStream,\n    crlfDelay: Infinity\n  });\n  // Note: we use the crlfDelay option to recognize all instances of CR LF\n  // ('\\r\\n') in input.txt as a single line break.\n\n  for await (const line of rl) {\n    // Each line in input.txt will be successively available here as `line`.\n    console.log(`Line from file: ${line}`);\n  }\n}\n\nprocessLineByLine();\n
\n

Alternatively, one could use the 'line' event:

\n
const fs = require('fs');\nconst readline = require('readline');\n\nconst rl = readline.createInterface({\n  input: fs.createReadStream('sample.txt'),\n  crlfDelay: Infinity\n});\n\nrl.on('line', (line) => {\n  console.log(`Line from file: ${line}`);\n});\n
\n

Currently, for-await-of loop can be a bit slower. If async / await\nflow and speed are both essential, a mixed approach can be applied:

\n
const { once } = require('events');\nconst { createReadStream } = require('fs');\nconst { createInterface } = require('readline');\n\n(async function processLineByLine() {\n  try {\n    const rl = createInterface({\n      input: createReadStream('big-file.txt'),\n      crlfDelay: Infinity\n    });\n\n    rl.on('line', (line) => {\n      // Process the line.\n    });\n\n    await once(rl, 'close');\n\n    console.log('File processed.');\n  } catch (err) {\n    console.error(err);\n  }\n})();\n
" } ], "type": "module", "displayName": "Readline" } ] }