Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Node .js read line by line


May 10, 2021 Node.js


Table of contents


Read line by line

This section describes .js readline module, which provides an interface.

稳定性: 2 - 不稳定

You require('readline') Readline reads a stream, such as process.stdin

Here's how to access the module:

const readline = require('readline');

Once you open this module, the node program will not terminate until you close the interface. The following code shows how elegant the exit program is:

var readline = require('readline');

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question("What do you think of node.js? ", function(answer) {
  // TODO: Log the answer in a database
  console.log("Thank you for your valuable feedback:", answer);

  rl.close();
});

readline.createInterface(options)

Create a readline-by-read Interface instance. The parameter "options" object has the following values:

  • input - Listen to a readable stream (required).

  • output - Writeable stream to be written to readline data (optional).

  • completer - an optional function for Tab auto-complement. See the example below.

  • terminal - If you want to treat input and output streams the same as output set to true. input I t is also transcoded by ANSI/VT100. By default, check isTTY is output on the output stream.

completer the entry to the current row and should return an array of 2 records.

  1. An array of strings that match the current input complement

  2. The substring used to match

In the end [[substr1, substr2, ...], originalsubstring] like this: .

Example:

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

At the same completer can run asynchronously, at which point two parameters are received:

function completer(linePartial, callback) {
  callback(null, [['123'], linePartial]);
}

To accept user input, createInterface process.stdin process.stdout

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

If you have a readline instance, you usually listen for "line"

If the instance parameter terminal and true output.columns output stream is optimally compatible, and when the columns change process.stdout does so automatically when it is TTY), "resize" output stream.

Class: Interface

Represents a class that contains a readline interface for the input/output stream.

rl.setPrompt(prompt)

Set the prompt, for example, when you run node the command line again, you can see >

rl.prompt([preserveCursor])

Prepare readline for user input, and enter setPrompt option method oh new line, between where the user has a new place to enter. Set preserveCursor true the current cursor from reset to 0

If you pause, you can also reset the input input stream input createInterface

When createInterface the output is not rewritten if output is set to null or undefined

rl.question(query, callback)

query which triggers callback after the callback After the user is shown the qury, the callback is called after the user's answer callback

If you pause, you can also reset the input input stream input createInterface

When createInterface the output is not rewritten if output is set to null or undefined

Example:

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

rl.pause()

Pause the input input stream for progressive input be restarted if needed.

Note that this does not immediately pause the flow. Pause is pause and many events are triggered, line

rl.resume()

Recover Readline input stream.

rl.close()

Close Interface instance and discard the control input and output stream. The "close" event is triggered.

rl.write(data[, key])

After createInterface data data data output output stream unless output null or undefined output key is an object that represents a sequence of keys;

This input be resumed after the input input stream is paused.

Example:

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

Events

Event: 'line'

function (line) {}

input input stream is triggered when it receives a \n usually because the user knocks on the return or return key. This is a good way to listen for user input.

Examples of line

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

Event: 'pause'

function () {}

This input triggered when the input input stream is paused.

The input stream is also triggered when it is SIGCONT (See SIGTSTP SIGCONT

Examples of pause

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

Event: 'resume'

function () {}

This input triggered when the input input stream is restored.

Examples of listening to resume

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

Event: 'close'

function () {}

The close() triggered when it is called.

The input input stream is triggered when it receives an "end" event. O nce triggered, you can think of Interface instance as over. For input the input input ^D it is called EOT

If SIGINT event listener, this event is also triggered when the input input stream receives the input stream , which is called ^C SIGINT

Event: 'SIGINT'

function () {}

The input input stream is ^C receives the sG, which is called SIGINT If SIGINT event listener, the pause event is triggered when the input input stream receives SIGINT (which is called SIGINT pause

Examples of SIGINT

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

Event: 'SIGTSTP'

function () {}

Not available in Windows

The input input stream is triggered when it receives ^Z which is SIGTSTP If SIGINT event listener, when the input input stream SIGTSTP the program switches to the background.

Pause and SIGCONT events are pause the program is recovered via fg You can use either event to restore the flow.

Pause and SIGCONT events are not triggered pause is paused before the process switches to the background.

Examples SIGTSTP

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

Event: 'SIGCONT'

function () {}

Not available in Windows

Triggered as soon as the input stream contains a .Z and switches to the background. I s used as SIGTSTP and then continues fg(1) This event can be triggered if the stream is not paused before the program switches to the background.

Examples SIGCONT

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

Example: Tiny CLI

The following example shows how all of these methods are command-line interfaces:

var readline = require('readline'),
    rl = readline.createInterface(process.stdin, process.stdout);

rl.setPrompt('OHAI> ');
rl.prompt();

rl.on('line', function(line) {
  switch(line.trim()) {
    case 'hello':
      console.log('world!');
      break;
    default:
      console.log('Say what? I might have heard `' + line.trim() + '`');
      break;
  }
  rl.prompt();
}).on('close', function() {
  console.log('Have a great day!');
  process.exit(0);
});

readline.cursorTo(stream, x, y)

In the TTY stream, move the cursor to the specified location.

readline.moveCursor(stream, dx, dy)

In the TTY stream, move the cursor to the relative position of the current position.

readline.clearLine(stream, dir)

Empty the rows in the TTY stream that specify the direction. dir the following value:

  • -1 - From cursor to left
  • 1 - From cursor to right
  • 0 - Full line

readline.clearScreenDown(stream)

Empty the content on the screen from the current cursor position.