逐行读取


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

要使用基于 promise 的 API:

¥To use the promise-based APIs:

import * as readline from 'node:readline/promises';const readline = require('node:readline/promises');

要使用回调和同步的 API:

¥To use the callback and sync APIs:

import * as readline from 'node:readline';const readline = require('node:readline');

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

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

import * as readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';

const rl = readline.createInterface({ input, output });

const answer = await rl.question('What do you think of Node.js? ');

console.log(`Thank you for your valuable feedback: ${answer}`);

rl.close();const readline = require('node:readline');
const { stdin: input, stdout: output } = require('node:process');

const rl = readline.createInterface({ input, output });

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.