readlinePromises.createInterface(options)


  • options <Object>
    • input <stream.Readable> 要监听的 可读的 流。此选项为_必填_。
    • output <stream.Writable> 写入 readline 数据的 可写 流。
    • 'completer' <Function> 用于制表表自动补全的可选函数。
    • terminal <boolean> true 如果 inputoutput 流应该被当作 TTY 处理,并向其写入 ANSI/VT100 转义代码。 默认值: 在实例化时检查 output 流的 isTTY
    • history <string[]> 初始历史记录行列表。只有当用户或内部 output 检查将 terminal 设置为 true 时,此选项才有意义,否则历史缓存机制根本不会被初始化。默认值: []
    • historySize <number> 保留的历史行的最大数量。要禁用历史记录,将此值设置为 0。只有当用户或内部的 output 检查将 terminal 设置为 true 时,此选项才有意义,否则历史缓存机制根本不会初始化。 默认值: 30
    • removeHistoryDuplicates <boolean> 如果为 true,当向历史记录列表添加新输入行时,如果与旧的输入重复,则会从列表中删除旧的那一行。默认值: false
    • prompt <string> 要使用的提示字符串。默认值: '> '
    • crlfDelay <number> 如果 之间的延迟超过 crlfDelay 毫秒,则 都会被视为单独的行结束输入。crlfDelay 将被强制转换为不小于 100 的数字。它可以设置为 Infinity,在这种情况下, 后跟 将始终被视为单个换行符(对于使用 行分隔符的 读取文件 来说,这可能是合理的)。默认值: 100
    • escapeCodeTimeout <number> readlinePromises 等待一个字符的时间(当读取模糊键序列时,以毫秒为单位,该键序列既可以使用到目前为止读取的输入形成完整键序列,也可以接受额外输入以完成更长的键序列)。 默认值: 500
    • tabSize <integer> 制表符等于的空格数(最少为 1)。 默认值: 8
    • signal <AbortSignal> 允许使用 AbortSignal 关闭接口。
  • 返回:<readlinePromises.Interface>

readlinePromises.createInterface() 方法会创建一个新的 readlinePromises.Interface 实例。

【The readlinePromises.createInterface() method creates a new readlinePromises.Interface instance.】

import { createInterface } from 'node:readline/promises';
import { stdin, stdout } from 'node:process';
const rl = createInterface({
  input: stdin,
  output: stdout,
});const { createInterface } = require('node:readline/promises');
const rl = createInterface({
  input: process.stdin,
  output: process.stdout,
});

一旦创建了 readlinePromises.Interface 实例,最常见的情况是监听 'line' 事件:

【Once the readlinePromises.Interface instance is created, the most common case is to listen for the 'line' event:】

rl.on('line', (line) => {
  console.log(`Received: ${line}`);
}); 

如果此实例的 terminaltrue,那么 output 流如果定义了 output.columns 属性并在列数发生变化时或变化时触发 output'resize' 事件,将获得最佳兼容性(process.stdout 在作为 TTY 时会自动执行此操作)。

【If terminal is true for this instance then the output stream will get the best compatibility if it defines an output.columns property and emits a 'resize' event on the output if or when the columns ever change (process.stdout does this automatically when it is a TTY).】