require('readline') 逐行读取可用于从命令行读取、从文件逐行读取写入等
readline 模块的基本用法:
const readline = require('readline');const rl = readline.createInterface({ input: process.stdin, output: process.stdout});
通过 readline.createInterface(options) 方法创建一个新的 readline.Interface 实例来实现逐行读取。
options
input
<Readable> 要监听的。该选项是必需的。output
<Writable> 要写入逐行读取数据的。completer
一个可选的函数,用于 Tab 自动补全。terminal
如果input
和output
应被当作一个 TTY,且要写入 ANSI/VT100 转换的代码,则设为true
。 默认为实例化时在output
流上检查isTTY
。historySize
保留的历史行数的最大数量。 设为0
可禁用历史记录。 该选项只有当terminal
被用户或内部output
设为true
时才有意义,否则历史缓存机制不会被初始化。 默认为30
。prompt
- 要使用的提示字符串。默认为'> '
。crlfDelay
如果\r
与\n
之间的延迟超过crlfDelay
毫秒,则\r
和\n
都会被当作换行分隔符。crlfDelay
will be coerced to a number no less than100
. It can be set toInfinity
, in which case\r
followed by\n
will always be considered a single newline (which may be reasonable for with\r\n
line delimiter). 默认为100
毫秒。removeHistoryDuplicates
Iftrue
, when a new input line added to the history list duplicates an older one, this removes the older line from the list. 默认为false
。
主要方法:
rl.close()
rl.close() 方法会关闭 readline.Interface 实例,且撤回对 input 和 output 流的控制。 被调用时,'close' 事件会被触发。
rl.pause()
rl.pause() 方法会暂停 input 流,且稍后需要时可被恢复。
rl.prompt([preserveCursor])
preserveCursor <boolean> 如果为 true,则阻止光标落点被设为 0
rl.prompt() 方法会在 output 流中新的一行写入 readline.Interface 实例配置后的 prompt
rl.resume()
如果 input 流已被暂停,则 rl.resume() 方法会恢复 input 流。
rl.write(data[, key])
data
key
ctrl
如果为true
则表示<ctrl>
键。meta
如果为true
则表示<Meta>
键。shift
如果为true
则表示<Shift>
键。name
一个按键的名称。
rl.write('删除这个!');// 模拟 Ctrl+u 删除写入的前一行。rl.write(null, { ctrl: true, name: 'u' });
主要事件:
'close' 事件
当 'close' 事件被触发时,readline.Interface 实例应当被视为已结束
'line' 事件
每当 input 流接收到接收行结束符(\n、\r 或 \r\n)时触发 'line' 事件。
通常发生在用户按下 <Enter> 键或 <Return> 键。 监听器函数被调用时会带上一个包含接收的那一行输入的字符串。
rl.on('line', (input) => { console.log(`接收到:${input}`);});
'pause' 事件
当以下之一发生时触发 'pause'
事件:
input
流被暂停。input
流不是暂停的,且接收到SIGCONT
事件。(详见 事件和 事件)
监听器函数被调用时不传入任何参数。
'resume' 事件
每当 input
流被恢复时触发 'resume'
事件。
监听器函数被调用时不传入任何参数。
'SIGINT' 事件
每当 input
流接收到一个 <ctrl>-C
输入(通常被称为 SIGINT
)时,触发 'SIGINT'
事件。 当 input
流接收到一个 SIGINT
时,如果没有注册 'SIGINT'
事件监听器,则 'pause'
事件会被触发。
监听器函数被调用时不传入任何参数。
'SIGCONT' 事件
当一个 Node.js 进程使用 <ctrl>-Z
(也就是 SIGTSTP
)移入后台之后再使用 移回前台时,触发 'SIGCONT'
事件。
如果 input
流在 SIGTSTP
请求之前被暂停,则事件不会被触发。
监听器函数被调用时不传入任何参数。
'SIGTSTP' 事件
每当 input
流接收到一个 <ctrl>-Z
输入(通常被称为 SIGTSTP
)时,触发 'SIGTSTP'
事件。 当 input
流接收到一个 SIGTSTP
时,如果没有注册 'SIGTSTP'
事件监听器,则 Node.js 进程会被发送到后台。
当程序使用 恢复时,'pause'
和 SIGCONT
事件会被触发。 这可被用来恢复 input
流。
如果 input
流在进程被发送到后台之前被暂停,则 'pause'
和 SIGCONT
事件不会被触发。
监听器函数被调用时不传入任何参数。