{ "source": "doc/api/readline.md", "modules": [ { "textRaw": "Readline", "name": "readline", "stability": 2, "stabilityText": "Stable", "desc": "
To use this module, do require('readline')
. Readline allows reading of a\nstream (such as [process.stdin
][]) on a line-by-line basis.
Note that once you've invoked this module, your Node.js program will not\nterminate until you've closed the interface. Here's how to allow your\nprogram to gracefully exit:
\nconst 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",
"classes": [
{
"textRaw": "Class: Interface",
"type": "class",
"name": "Interface",
"meta": {
"added": [
"v0.1.104"
]
},
"desc": "The class that represents a readline interface with an input and output\nstream.
\n", "methods": [ { "textRaw": "rl.close()", "type": "method", "name": "close", "meta": { "added": [ "v0.1.98" ] }, "desc": "Closes the Interface
instance, relinquishing control on the input
and\noutput
streams. The 'close'
event will also be emitted.
Pauses the readline input
stream, allowing it to be resumed later if needed.
Note that this doesn't immediately pause the stream of events. Several events may\nbe emitted after calling pause
, including line
.
Readies readline for input from the user, putting the current setPrompt
\noptions on a new line, giving the user a new spot to write. Set preserveCursor
\nto true
to prevent the cursor placement being reset to 0
.
This will also resume the input
stream used with createInterface
if it has\nbeen paused.
If output
is set to null
or undefined
when calling createInterface
, the\nprompt is not written.
Prepends the prompt with query
and invokes callback
with the user's\nresponse. Displays the query to the user, and then invokes callback
\nwith the user's response after it has been typed.
This will also resume the input
stream used with createInterface
if\nit has been paused.
If output
is set to null
or undefined
when calling createInterface
,\nnothing is displayed.
Example usage:
\nrl.question('What is your favorite food?', (answer) => {\n console.log(`Oh, so your favorite food is ${answer}`);\n});\n
\n",
"signatures": [
{
"params": [
{
"name": "query"
},
{
"name": "callback"
}
]
}
]
},
{
"textRaw": "rl.resume()",
"type": "method",
"name": "resume",
"meta": {
"added": [
"v0.3.4"
]
},
"desc": "Resumes the readline input
stream.
Sets the prompt, for example when you run node
on the command line, you see\n>
, which is Node.js's prompt.
Writes data
to output
stream, unless output
is set to null
or\nundefined
when calling createInterface
. key
is an object literal to\nrepresent a key sequence; available if the terminal is a TTY.
This will also resume the input
stream if it has been paused.
Example:
\nrl.write('Delete me!');\n// Simulate ctrl+u to delete the line written previously\nrl.write(null, {ctrl: true, name: 'u'});\n
\n",
"signatures": [
{
"params": [
{
"name": "data"
},
{
"name": "key",
"optional": true
}
]
}
]
}
]
}
],
"modules": [
{
"textRaw": "Events",
"name": "events",
"events": [
{
"textRaw": "Event: 'close'",
"type": "event",
"name": "close",
"meta": {
"added": [
"v0.1.98"
]
},
"desc": "function () {}
Emitted when close()
is called.
Also emitted when the input
stream receives its 'end'
event. The Interface
\ninstance should be considered "finished" once this is emitted. For example, when\nthe input
stream receives ^D
, respectively known as EOT
.
This event is also called if there is no SIGINT
event listener present when\nthe input
stream receives a ^C
, respectively known as SIGINT
.
function (line) {}
Emitted whenever the input
stream receives an end of line (\\n
, \\r
, or\n\\r\\n
), usually received when the user hits enter, or return. This is a good\nhook to listen for user input.
Example of listening for 'line'
:
rl.on('line', (cmd) => {\n console.log(`You just typed: ${cmd}`);\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'pause'",
"type": "event",
"name": "pause",
"meta": {
"added": [
"v0.7.5"
]
},
"desc": "function () {}
Emitted whenever the input
stream is paused.
Also emitted whenever the input
stream is not paused and receives the\nSIGCONT
event. (See events SIGTSTP
and SIGCONT
)
Example of listening for 'pause'
:
rl.on('pause', () => {\n console.log('Readline paused.');\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'resume'",
"type": "event",
"name": "resume",
"meta": {
"added": [
"v0.7.5"
]
},
"desc": "function () {}
Emitted whenever the input
stream is resumed.
Example of listening for 'resume'
:
rl.on('resume', () => {\n console.log('Readline resumed.');\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'SIGCONT'",
"type": "event",
"name": "SIGCONT",
"meta": {
"added": [
"v0.7.5"
]
},
"desc": "function () {}
This does not work on Windows.
\nEmitted whenever the input
stream is sent to the background with ^Z
,\nrespectively known as SIGTSTP
, and then continued with fg(1)
. This event\nonly emits if the stream was not paused before sending the program to the\nbackground.
Example of listening for SIGCONT
:
rl.on('SIGCONT', () => {\n // `prompt` will automatically resume the stream\n rl.prompt();\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'SIGINT'",
"type": "event",
"name": "SIGINT",
"meta": {
"added": [
"v0.3.0"
]
},
"desc": "function () {}
Emitted whenever the input
stream receives a ^C
, respectively known as\nSIGINT
. If there is no SIGINT
event listener present when the input
\nstream receives a SIGINT
, pause
will be triggered.
Example of listening for SIGINT
:
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
\n",
"params": []
},
{
"textRaw": "Event: 'SIGTSTP'",
"type": "event",
"name": "SIGTSTP",
"meta": {
"added": [
"v0.7.5"
]
},
"desc": "function () {}
This does not work on Windows.
\nEmitted whenever the input
stream receives a ^Z
, respectively known as\nSIGTSTP
. If there is no SIGTSTP
event listener present when the input
\nstream receives a SIGTSTP
, the program will be sent to the background.
When the program is resumed with fg
, the 'pause'
and SIGCONT
events will be\nemitted. You can use either to resume the stream.
The 'pause'
and SIGCONT
events will not be triggered if the stream was paused\nbefore the program was sent to the background.
Example of listening for SIGTSTP
:
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
\nHere's an example of how to use all these together to craft a tiny command\nline interface:
\nconst readline = require('readline');\nconst rl = readline.createInterface(process.stdin, process.stdout);\n\nrl.setPrompt('OHAI> ');\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
\nA common case for readline
's input
option is to pass a filesystem readable\nstream to it. This is how one could craft line-by-line parsing of a file:
const readline = require('readline');\nconst fs = require('fs');\n\nconst rl = readline.createInterface({\n input: fs.createReadStream('sample.txt')\n});\n\nrl.on('line', (line) => {\n console.log('Line from file:', line);\n});\n
\n",
"params": []
}
],
"type": "module",
"displayName": "Events"
}
],
"methods": [
{
"textRaw": "readline.clearLine(stream, dir)",
"type": "method",
"name": "clearLine",
"meta": {
"added": [
"v0.7.7"
]
},
"desc": "Clears current line of given TTY stream in a specified direction.\ndir
should have one of following values:
-1
- to the left from cursor1
- to the right from cursor0
- the entire lineClears the screen from the current position of the cursor down.
\n", "signatures": [ { "params": [ { "name": "stream" } ] } ] }, { "textRaw": "readline.createInterface(options)", "type": "method", "name": "createInterface", "meta": { "added": [ "v0.1.98" ] }, "desc": "Creates a readline Interface
instance. Accepts an options
Object that takes\nthe following values:
input
- the readable stream to listen to (Required).
output
- the writable stream to write readline data to (Optional).
completer
- an optional function that is used for Tab autocompletion. See\nbelow for an example of using this.
terminal
- pass true
if the input
and output
streams should be\ntreated like a TTY, and have ANSI/VT100 escape codes written to it.\nDefaults to checking isTTY
on the output
stream upon instantiation.
historySize
- maximum number of history lines retained. Defaults to 30
.
The completer
function is given the current line entered by the user, and\nis supposed to return an Array with 2 entries:
An Array with matching entries for the completion.
\nThe substring that was used for the matching.
\nWhich ends up looking something like:\n[[substr1, substr2, ...], originalsubstring]
.
Example:
\nfunction completer(line) {\n var completions = '.help .error .exit .quit .q'.split(' ')\n var hits = completions.filter((c) => { return c.indexOf(line) == 0 })\n // show all completions if none found\n return [hits.length ? hits : completions, line]\n}\n
\nAlso completer
can be run in async mode if it accepts two arguments:
function completer(linePartial, callback) {\n callback(null, [['123'], linePartial]);\n}\n
\ncreateInterface
is commonly used with [process.stdin
][] and\n[process.stdout
][] in order to accept user input:
const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n
\nOnce you have a readline instance, you most commonly listen for the\n'line'
event.
If terminal
is true
for this instance then the output
stream will get\nthe best compatibility if it defines an output.columns
property, and fires\na 'resize'
event on the output
if/when the columns ever change\n([process.stdout
][] does this automatically when it is a TTY).
Move cursor to the specified position in a given TTY stream.
\n", "signatures": [ { "params": [ { "name": "stream" }, { "name": "x" }, { "name": "y" } ] } ] }, { "textRaw": "readline.emitKeypressEvents(stream[, interface])", "type": "method", "name": "emitKeypressEvents", "meta": { "added": [ "v0.7.7" ] }, "desc": "Causes stream
to begin emitting 'keypress'
events corresponding to its\ninput.\nOptionally, interface
specifies a readline.Interface
instance for which\nautocompletion is disabled when copy-pasted input is detected.
Move cursor relative to it's current position in a given TTY stream.
\n", "signatures": [ { "params": [ { "name": "stream" }, { "name": "dx" }, { "name": "dy" } ] } ] } ], "type": "module", "displayName": "Readline" } ] }