Nodejs--readline(逐行读取)

require('readline') 逐行读取可用于从命令行读取、从文件逐行读取写入html

readline 模块的基本用法:

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

经过 readline.createInterface(options) 方法建立一个新的 readline.Interface 实例来实现逐行读取。node

options <Object>linux

  • input <Readable> 要监听的可读流。该选项是必需的。
  • output <Writable> 要写入逐行读取数据的可写流
  • completer <Function> 一个可选的函数,用于 Tab 自动补全。
  • terminal <boolean> 若是 input 和 output 应被看成一个 TTY,且要写入 ANSI/VT100 转换的代码,则设为 true。 默认为实例化时在 output 流上检查 isTTY
  • historySize <number> 保留的历史行数的最大数量。 设为 0 可禁用历史记录。 该选项只有当 terminal 被用户或内部 output 设为 true 时才有意义,不然历史缓存机制不会被初始化。 默认为 30
  • prompt - 要使用的提示字符串。默认为 '> '
  • crlfDelay <number> 若是 \r 与 \n 之间的延迟超过 crlfDelay 毫秒,则 \r 和 \n 都会被看成换行分隔符。 crlfDelay will be coerced to a number no less than 100. It can be set to Infinity, in which case \r followed by \n will always be considered a single newline (which may be reasonable for reading files with \r\n line delimiter). 默认为 100 毫秒。
  • removeHistoryDuplicates <boolean> If true, 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' 事件会被触发。api

rl.pause()

rl.pause() 方法会暂停 input 流,且稍后须要时可被恢复。缓存

rl.prompt([preserveCursor])

preserveCursor <boolean> 若是为 true,则阻止光标落点被设为 0less

rl.prompt() 方法会在 output 流中新的一行写入 readline.Interface 实例配置后的 promptide

rl.resume()

若是 input 流已被暂停,则 rl.resume() 方法会恢复 input 流。函数

rl.write(data[, key])

rl.write('删除这个!');
// 模拟 Ctrl+u 删除写入的前一行。
rl.write(null, { ctrl: true, name: 'u' });

 

主要事件:

'close' 事件

当 'close' 事件被触发时,readline.Interface 实例应当被视为已结束ui

'line' 事件

每当 input 流接收到接收行结束符(\n、\r 或 \r\n)时触发 'line' 事件。this

一般发生在用户按下 <Enter> 键或 <Return> 键。 监听器函数被调用时会带上一个包含接收的那一行输入的字符串。

rl.on('line', (input) => {
  console.log(`接收到:${input}`);
});

'pause' 事件

当如下之一发生时触发 'pause' 事件:

  • input 流被暂停。
  • input 流不是暂停的,且接收到 SIGCONT 事件。(详见 SIGTSTP 事件和 SIGCONT 事件)

监听器函数被调用时不传入任何参数。

'resume' 事件

每当 input 流被恢复时触发 'resume' 事件。

监听器函数被调用时不传入任何参数。

'SIGINT' 事件

每当 input 流接收到一个 <ctrl>-C 输入(一般被称为 SIGINT)时,触发 'SIGINT' 事件。 当 input 流接收到一个 SIGINT 时,若是没有注册 'SIGINT' 事件监听器,则 'pause' 事件会被触发。

监听器函数被调用时不传入任何参数。

'SIGCONT' 事件

当一个 Node.js 进程使用 <ctrl>-Z(也就是 SIGTSTP)移入后台以后再使用 fg(1p) 移回前台时,触发 'SIGCONT' 事件。

若是 input 流在 SIGTSTP 请求以前被暂停,则事件不会被触发。

监听器函数被调用时不传入任何参数。

'SIGTSTP' 事件

每当 input 流接收到一个 <ctrl>-Z 输入(一般被称为 SIGTSTP)时,触发 'SIGTSTP' 事件。 当 input 流接收到一个 SIGTSTP 时,若是没有注册 'SIGTSTP' 事件监听器,则 Node.js 进程会被发送到后台。

当程序使用 fg(1p) 恢复时,'pause' 和 SIGCONT 事件会被触发。 这可被用来恢复 input 流。

若是 input 流在进程被发送到后台以前被暂停,则 'pause' 和 SIGCONT 事件不会被触发。

监听器函数被调用时不传入任何参数。

相关文章
相关标签/搜索