readline 逐行读取


稳定性: 2 - 稳定

源代码: lib/readline.js

readline 模块提供了用于从可读流(例如 process.stdin)每次一行地读取数据的接口。 可以使用以下方式访问它:

const readline = require('readline');

下面的简单示例阐明了 readline 模块的基本用法。

const readline = require('readline');

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

rl.question('What do you think of Node.js? ', (answer) => {
  // TODO:记录答案到数据库中
  console.log(`Thank you for your valuable feedback: ${answer}`);

  rl.close();
});

一旦调用此代码,则 Node.js 应用程序将不会终止,直到 readline.Interface 关闭,因为接口在 input 流上等待接收数据。

Stability: 2 - Stable

Source Code: lib/readline.js

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

const readline = require('readline');

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

const readline = require('readline');

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

rl.question('What do you think of Node.js? ', (answer) => {
  // TODO: Log the answer in a database
  console.log(`Thank you for your valuable feedback: ${answer}`);

  rl.close();
});

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