逐行读取


¥Readline

稳定性: 2 - 稳定的

¥Stability: 2 - Stable

源代码: lib/readline.js

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

¥The node: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('node:readline'); 

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

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

const readline = require('node: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();
}); 

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

¥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.