readline 逐行读取


稳定性: 2 - 稳定

源代码: lib/readline.js

node:readline 模块提供了用于从可读流(例如 process.stdin)每次一行地读取数据的接口。

要使用基于 promise 的 API:

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

要使用回调和同步的 API:

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

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

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:记录答案到数据库中
  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 node:readline module provides an interface for reading data from a Readable stream (such as process.stdin) one line at a time.

To use the promise-based APIs:

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

To use the callback and sync APIs:

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

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.