Readline

  1. Stability: 2 - Unstable

To use this module, do require('readline'). Readline allows reading of a
stream (such as process.stdin) on a line-by-line basis.

Note that once you’ve invoked this module, your node program will not
terminate until you’ve closed the interface. Here’s how to allow your
program to gracefully exit:

  1. var readline = require('readline');
  2. var rl = readline.createInterface({
  3. input: process.stdin,
  4. output: process.stdout
  5. });
  6. rl.question("What do you think of node.js? ", function(answer) {
  7. // TODO: Log the answer in a database
  8. console.log("Thank you for your valuable feedback:", answer);
  9. rl.close();
  10. });

readline.createInterface(options)

Creates a readline Interface instance. Accepts an “options” Object that takes
the 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
    below for an example of using this.

  • terminal - pass true if the input and output streams should be
    treated like a TTY, and have ANSI/VT100 escape codes written to it.
    Defaults to checking isTTY on the output stream upon instantiation.

The completer function is given the current line entered by the user, and
is supposed to return an Array with 2 entries:

  1. An Array with matching entries for the completion.

  2. The substring that was used for the matching.

Which ends up looking something like:
[[substr1, substr2, ...], originalsubstring].

Example:

  1. function completer(line) {
  2. var completions = '.help .error .exit .quit .q'.split(' ')
  3. var hits = completions.filter(function(c) { return c.indexOf(line) == 0 })
  4. // show all completions if none found
  5. return [hits.length ? hits : completions, line]
  6. }

Also completer can be run in async mode if it accepts two arguments:

  1. function completer(linePartial, callback) {
  2. callback(null, [['123'], linePartial]);
  3. }

createInterface is commonly used with process.stdin and
process.stdout in order to accept user input:

  1. var readline = require('readline');
  2. var rl = readline.createInterface({
  3. input: process.stdin,
  4. output: process.stdout
  5. });

Once you have a readline instance, you most commonly listen for the
"line" event.

If terminal is true for this instance then the output stream will get
the best compatibility if it defines an output.columns property, and fires
a "resize" event on the output if/when the columns ever change
(process.stdout does this automatically when it is a TTY).

Class: Interface

The class that represents a readline interface with an input and output
stream.

rl.setPrompt(prompt)

Sets the prompt, for example when you run node on the command line, you see
>, which is node’s prompt.

rl.prompt([preserveCursor])

Readies readline for input from the user, putting the current setPrompt
options on a new line, giving the user a new spot to write. Set preserveCursor
to true to prevent the cursor placement being reset to 0.

This will also resume the input stream used with createInterface if it has
been paused.

If output is set to null or undefined when calling createInterface, the
prompt is not written.

rl.question(query, callback)

Prepends the prompt with query and invokes callback with the user’s
response. Displays the query to the user, and then invokes callback
with the user’s response after it has been typed.

This will also resume the input stream used with createInterface if
it has been paused.

If output is set to null or undefined when calling createInterface,
nothing is displayed.

Example usage:

  1. interface.question('What is your favorite food?', function(answer) {
  2. console.log('Oh, so your favorite food is ' + answer);
  3. });

rl.pause()

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 be emitted after calling pause, including line.

rl.resume()

Resumes the readline input stream.

rl.close()

Closes the Interface instance, relinquishing control on the input and
output streams. The “close” event will also be emitted.

rl.write(data[, key])

Writes data to output stream, unless output is set to null or
undefined when calling createInterface. key is an object literal to
represent a key sequence; available if the terminal is a TTY.

This will also resume the input stream if it has been paused.

Example:

  1. rl.write('Delete me!');
  2. // Simulate ctrl+u to delete the line written previously
  3. rl.write(null, {ctrl: true, name: 'u'});

Events

Event: ‘line’

function (line) {}

Emitted whenever the input stream receives a \n, usually received when the
user hits enter, or return. This is a good hook to listen for user input.

Example of listening for line:

  1. rl.on('line', function (cmd) {
  2. console.log('You just typed: '+cmd);
  3. });

Event: ‘pause’

function () {}

Emitted whenever the input stream is paused.

Also emitted whenever the input stream is not paused and receives the
SIGCONT event. (See events SIGTSTP and SIGCONT)

Example of listening for pause:

  1. rl.on('pause', function() {
  2. console.log('Readline paused.');
  3. });

Event: ‘resume’

function () {}

Emitted whenever the input stream is resumed.

Example of listening for resume:

  1. rl.on('resume', function() {
  2. console.log('Readline resumed.');
  3. });

Event: ‘close’

function () {}

Emitted when close() is called.

Also emitted when the input stream receives its “end” event. The Interface
instance should be considered “finished” once this is emitted. For example, when
the input stream receives ^D, respectively known as EOT.

This event is also called if there is no SIGINT event listener present when
the input stream receives a ^C, respectively known as SIGINT.

Event: ‘SIGINT’

function () {}

Emitted whenever the input stream receives a ^C, respectively known as
SIGINT. If there is no SIGINT event listener present when the input
stream receives a SIGINT, pause will be triggered.

Example of listening for SIGINT:

  1. rl.on('SIGINT', function() {
  2. rl.question('Are you sure you want to exit?', function(answer) {
  3. if (answer.match(/^y(es)?$/i)) rl.pause();
  4. });
  5. });

Event: ‘SIGTSTP’

function () {}

This does not work on Windows.

Emitted whenever the input stream receives a ^Z, respectively known as
SIGTSTP. If there is no SIGTSTP event listener present when the input
stream 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
emitted. You can use either to resume the stream.

The pause and SIGCONT events will not be triggered if the stream was paused
before the program was sent to the background.

Example of listening for SIGTSTP:

  1. rl.on('SIGTSTP', function() {
  2. // This will override SIGTSTP and prevent the program from going to the
  3. // background.
  4. console.log('Caught SIGTSTP.');
  5. });

Event: ‘SIGCONT’

function () {}

This does not work on Windows.

Emitted whenever the input stream is sent to the background with ^Z,
respectively known as SIGTSTP, and then continued with fg(1). This event
only emits if the stream was not paused before sending the program to the
background.

Example of listening for SIGCONT:

  1. rl.on('SIGCONT', function() {
  2. // `prompt` will automatically resume the stream
  3. rl.prompt();
  4. });

Example: Tiny CLI

Here’s an example of how to use all these together to craft a tiny command
line interface:

  1. var readline = require('readline'),
  2. rl = readline.createInterface(process.stdin, process.stdout);
  3. rl.setPrompt('OHAI> ');
  4. rl.prompt();
  5. rl.on('line', function(line) {
  6. switch(line.trim()) {
  7. case 'hello':
  8. console.log('world!');
  9. break;
  10. default:
  11. console.log('Say what? I might have heard `' + line.trim() + '`');
  12. break;
  13. }
  14. rl.prompt();
  15. }).on('close', function() {
  16. console.log('Have a great day!');
  17. process.exit(0);
  18. });

readline.cursorTo(stream, x, y)

Move cursor to the specified position in a given TTY stream.

readline.moveCursor(stream, dx, dy)

Move cursor relative to it’s current position in a given TTY stream.

readline.clearLine(stream, dir)

Clears current line of given TTY stream in a specified direction.
dir should have one of following values:

  • -1 - to the left from cursor
  • 1 - to the right from cursor
  • 0 - the entire line

readline.clearScreenDown(stream)

Clears the screen from the current position of the cursor down.