readline.createInterface(options)
options<Object>input<stream.Readable> 可读的 流可供收听。此选项为 必填。output<stream.Writable> 可写 流用于写入 readline 数据。completer<Function> 用于制表符自动补齐的可选功能。terminal<boolean>true如果input和output流应该被像 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> 如果\r和\n之间的延迟超过crlfDelay毫秒,\r和\n都会被视为独立的行尾输入。crlfDelay将被强制为不小于100的数字。它可以设置为Infinity,在这种情况下,\r后跟\n将始终被视为单个换行符(对于使用\r\n行分隔符的 读取文件 可能是合理的)。默认值:100。escapeCodeTimeout<number>readline持续时间将在读取模糊键序列时等待一个字符(以毫秒为单位,此字符既可以使用迄今为止读取的输入形成完整的键序列,也可以接受额外的输入以完成更长的键序列)。默认值:500。tabSize<integer> 一个制表符等于多少个空格(最少为1)。 默认值:8。signal<AbortSignal> 允许使用 AbortSignal 关闭接口。中止信号将内部调用接口上的close。
- 返回:<readline.Interface>
readline.createInterface() 方法创建一个新的 readline.Interface 实例。
🌐 The readline.createInterface() method creates a new readline.Interface
instance.
import { createInterface } from 'node:readline';
import { stdin, stdout } from 'node:process';
const rl = createInterface({
input: stdin,
output: stdout,
});const { createInterface } = require('node:readline');
const rl = createInterface({
input: process.stdin,
output: process.stdout,
});一旦创建了 readline.Interface 实例,最常见的情况是监听 'line' 事件:
🌐 Once the readline.Interface instance is created, the most common case is to
listen for the 'line' event:
rl.on('line', (line) => {
console.log(`Received: ${line}`);
}); 如果此实例的 terminal 为 true,那么 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).
在使用 stdin 作为输入创建 readline.Interface 时,程序不会终止,直到收到 文件结束字符。若想在不等待用户输入的情况下退出,请调用 process.stdin.unref()。
🌐 When creating a readline.Interface using stdin as input, the program
will not terminate until it receives an EOF character. To exit without
waiting for user input, call process.stdin.unref().