逐行读取


🌐 Readline

源代码: 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.