readline.createInterface(options)
options<Object>input<stream.Readable> 要监听的 可读的 流。此选项为 必填。output<stream.Writable> 要写入 readline 数据的 可写 流。completer<Function> 一个用于 Tab 自动补全的可选函数。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> 如果和之间的延迟超过crlfDelay毫秒,则和都将被视为单独的行结束输入。crlfDelay将被强制转换为不小于100的数字。它可以设置为Infinity,在这种情况下,后跟将始终被视为单个换行符(对于使用行分隔符的 读取文件 来说,这可能是合理的)。默认值: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.】
const readline = require('node:readline');
const rl = readline.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().】