Node.js v18.12.1 documentation


Table of contents

Readline#

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.node:readline模块提供了一个接口,用于一次一行地从Readable流(如process.stdin)中读取数据。

To use the promise-based APIs:要使用基于承诺的API:

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

To use the callback and sync APIs:要使用回调和同步API,请执行以下操作:

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

The following simple example illustrates the basic use of the node:readline module.下面的简单示例说明了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: 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.一旦调用此代码,Node.js应用程序将不会终止,直到readline.Interface关闭,因为该接口等待在input流上接收数据。