On this page

readline 逐行读取

History
Source Code: lib/readline.js

稳定性:2 - 稳定

node:readline 模块提供了一个接口,用于从 Readable 流(例如 process.stdin)中一次读取一行数据。

要使用基于 Promise 的 API:

要使用回调和同步 API:

以下简单示例说明了 node:readline 模块的基本用法。

import * as readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';

const rl = readline.createInterface({ input, output });

const answer = await rl.question('What do you think of Node.js? ');

console.log(`Thank you for your valuable feedback: ${answer}`);

rl.close();

一旦调用此代码,Node.js 应用程序将不会终止,直到 readline.Interface 被关闭,因为接口等待从 input 流接收数据。

C

InterfaceConstructor

History
class InterfaceConstructor extends EventEmitter

InterfaceConstructor 类的实例使用 readlinePromises.createInterface() 或 readline.createInterface() 方法构造。 每个实例都与一个 input Readable 流和一个 output Writable 流相关联。 output 流用于为到达的用户输入打印提示符, 并从 input 流中读取。

E

close

History

当发生以下情况之一时,将触发 'close' 事件:

  • 调用 rl.close() 方法,并且 InterfaceConstructor 实例已 放弃对 input 和 output 流的控制;
  • input 流收到 'end' 事件;
  • input 流收到 Ctrl+D 以表示 传输结束(EOT);
  • input 流收到 Ctrl+C 以发出 SIGINT 信号, 并且 InterfaceConstructor 实例上 没有注册 'SIGINT' 事件监听器。

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

一旦触发 'close' 事件,InterfaceConstructor 实例即 完成。

E

error

History

当与 node:readline Interface 关联的 input 流 发生错误时,将触发 'error' 事件。

调用监听器函数时,会将一个 Error 对象作为唯一参数传入。

E

line

History

每当 input 流接收到行尾输入 (\n、\r 或 \r\n)时,将触发 'line' 事件。这通常发生在用户 按下 Enter 或 Return 时。

如果已从流中读取了新数据,并且该流 在没有最终行尾标记的情况下结束,也会触发 'line' 事件。

调用监听器函数时,传入的字符串包含接收到的 那一行输入。

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

history

History

每当历史数组发生变化时,将触发 'history' 事件。

调用监听器函数时,会传入一个包含该历史数组的数组。 它将反映所有变化,包括由于 historySize 和 removeHistoryDuplicates 而添加的行和删除的行。

主要目的是让监听器能够持久化历史记录。 监听器也可以更改历史对象。这 对于阻止某些行(例如密码)被 添加到历史记录中可能很有用。

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

pause

History

当发生以下情况之一时,将触发 'pause' 事件:

  • input 流被暂停。
  • input 流未被暂停且收到 'SIGCONT' 事件。(参见 事件 'SIGTSTP' 和 'SIGCONT'。)

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

rl.on('pause', () => {
  console.log('Readline paused.');
});
E

resume

History

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

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

rl.on('resume', () => {
  console.log('Readline resumed.');
});
E

SIGCONT

History

当之前使用 Ctrl+Z(即 SIGTSTP)移入 后台的 Node.js 进程随后使用 fg(1p) 带回前台时, 将触发 'SIGCONT' 事件。

如果在 SIGTSTP 请求 之前 input 流已被暂停, 则不会触发此事件。

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

rl.on('SIGCONT', () => {
  // `prompt` 将自动恢复流
  rl.prompt();
});

'SIGCONT' 事件在 Windows 上 不 受支持。

E

SIGINT

History

每当 input 流接收到 通常称为 SIGINT 的 Ctrl+C 输入时,将触发 'SIGINT' 事件。如果 在 input 流收到 SIGINT 时未注册 'SIGINT' 事件监听器, 则将触发 'pause' 事件。

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

rl.on('SIGINT', () => {
  rl.question('Are you sure you want to exit? ', (answer) => {
    if (answer.match(/^y(es)?$/i)) rl.pause();
  });
});
E

SIGTSTP

History

当 input 流接收到 通常称为 SIGTSTP 的 Ctrl+Z 输入时,将触发 'SIGTSTP' 事件。如果 在 input 流收到 SIGTSTP 时未注册 'SIGTSTP' 事件监听器, 则 Node.js 进程将被送入后台。

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

如果在进程被送入后台之前 input 已被暂停, 则不会触发 'pause' 和 'SIGCONT' 事件。

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

rl.on('SIGTSTP', () => {
  // 这将覆盖 SIGTSTP 并阻止程序进入
  // 后台。
  console.log('Caught SIGTSTP.');
});

'SIGTSTP' 事件在 Windows 上 不 受支持。

M

rl.close

History
rl.close(): void

rl.close() 方法关闭 InterfaceConstructor 实例,并 放弃对 input 和 output 流的控制。调用时, 将触发 'close' 事件。

调用 rl.close() 不会立即阻止 InterfaceConstructor 实例 触发其他事件(包括 'line')。

M

rl[Symbol.dispose]

History
rl[Symbol.dispose](): void

rl.close() 的别名。

M

rl.pause

History
rl.pause(): void

rl.pause() 方法暂停 input 流,以便 必要时稍后恢复。

调用 rl.pause() 不会立即阻止 InterfaceConstructor 实例 触发其他事件(包括 'line')。

M

rl.prompt

History
rl.prompt(preserveCursor?): void
Attributes
preserveCursor:<boolean>
如果为  true ,则阻止光标位置 被重置为 0 。

rl.prompt() 方法将 InterfaceConstructor 实例配置的 prompt 写入 output 的新行中,以便为用户提供一个新的 输入位置。

调用时,如果 input 流已被暂停,rl.prompt() 将 恢复该流。

如果 InterfaceConstructor 创建时 output 设置为 null 或 undefined,则不会写入提示符。

M

rl.resume

History
rl.resume(): void

如果 input 流已被暂停,rl.resume() 方法将恢复该流。

M

rl.setPrompt

History
rl.setPrompt(prompt): void
Attributes
prompt:<string>

rl.setPrompt() 方法设置提示符,该提示符将在 每次调用 rl.prompt() 时写入 output。

M

rl.getPrompt

History
rl.getPrompt(): void
  • 返回:<string> 当前提示符字符串

rl.getPrompt() 方法返回 rl.prompt() 当前使用的提示符。

M

rl.write

History
rl.write(data, key?): void
Attributes
true 表示 Ctrl 键。
true 表示 Meta 键。
shift:<boolean>
true 表示 Shift 键。
按键的名称。

rl.write() 方法会将 data 或由 key 标识的键序列 写入 output。仅当 output 是 TTY 文本终端时才支持 key 参数。有关组合键的 列表,请参见 TTY 按键绑定。

如果指定了 key,则忽略 data。

调用时,如果 input 流已被暂停,rl.write() 将 恢复该流。

如果 InterfaceConstructor 创建时 output 设置为 null 或 undefined,则不会写入 data 和 key。

rl.write('Delete this!');
// 模拟 Ctrl+U 以删除之前写入的行
rl.write(null, { ctrl: true, name: 'u' });

rl.write() 方法将数据写入 readline Interface 的 input,就好像它是由用户提供的一样。

rl[Symbol.asyncIterator](): void

创建一个 AsyncIterator 对象,该对象以字符串形式迭代输入 流中的每一行。此方法允许通过 for await...of 循环 对 InterfaceConstructor 对象进行异步迭代。

输入流中的错误不会被转发。

如果使用 break、throw 或 return 终止循环, 则将调用 rl.close()。换句话说,遍历 InterfaceConstructor 将始终完整消耗输入流。

性能无法与传统的 'line' 事件 API 相提并论。对于性能敏感的应用, 请改用 'line' 事件。

async function processLineByLine() {
  const rl = readline.createInterface({
    // ...
  });

  for await (const line of rl) {
    // readline 输入中的每一行将在此处依次作为
    // `line` 提供。
  }
}

readline.createInterface() 一旦调用就会开始消耗输入流。 在接口创建与异步迭代之间进行异步操作 可能会导致遗漏某些行。

当前由 node 处理的输入数据。

当从 TTY 流收集输入时,这将跟踪当前光标 line 事件触发之前已处理的当前值。 一旦触发 line 事件,该属性将 变为空字符串。

请注意,在实例运行期间修改该值可能会 产生意外后果,除非同时控制 rl.cursor。

如果不使用 TTY 流作为输入,请使用 'line' 事件。

一种可能的用例如下:

const values = ['lorem ipsum', 'dolor sit amet'];
const rl = readline.createInterface(process.stdin);
const showResults = debounce(() => {
  console.log(
    '\n',
    values.filter((val) => val.startsWith(rl.line)).join(' '),
  );
}, 300);
process.stdin.on('keypress', (c, k) => {
  showResults();
});
P

rl.cursor

History

相对于 rl.line 的光标位置。

当从 TTY 流读取输入时,这将跟踪当前光标 在输入字符串中的位置。光标位置决定了 处理输入时将修改的输入字符串部分, 以及终端插入光标所在的列。

M

rl.getCursorPos

History
rl.getCursorPos(): void
  • 返回: <Object>
    Attributes
    光标当前所在提示符的行
    光标当前所在的屏幕列

返回光标相对于输入提示符 + 字符串的实际位置。 长输入(换行)字符串以及多行提示符 均包含在计算中。

C

readlinePromises.Interface

History
class readlinePromises.Interface extends readline.InterfaceConstructor

readlinePromises.Interface 类的实例使用 readlinePromises.createInterface() 方法构造。每个实例都与一个 input Readable 流和一个 output Writable 流相关联。 output 流用于为到达的用户输入打印提示符, 并从 input 流中读取。

M

rl.question

History
rl.question(query, options?): void
Attributes
query:<string>
要写入  output 的语句或查询, 位于提示符之前。
options:<Object>
可选,允许使用  AbortSignal 取消 question() 。

rl.question() 方法通过将 query 写入 output 来显示它, 等待在 input 上提供用户输入,然后调用 callback 函数,并将提供的输入作为第一个参数传入。

调用时,如果 input 流已被暂停,rl.question() 将 恢复该流。

如果 readlinePromises.Interface 创建时 output 设置为 null 或 undefined,则不会写入 query。

如果在 rl.close() 之后调用提问,则返回一个被拒绝的 Promise。

用法示例:

const answer = await rl.question('What is your favorite food? ');
console.log(`Oh, so your favorite food is ${answer}`);

使用 AbortSignal 取消提问。

const signal = AbortSignal.timeout(10_000);

signal.addEventListener('abort', () => {
  console.log('The food question timed out');
}, { once: true });

const answer = await rl.question('What is your favorite food? ', { signal });
console.log(`Oh, so your favorite food is ${answer}`);
C

readlinePromises.Readline

History
C

readlinePromises.Readline Constructor

History
new readlinePromises.Readline(stream, options?): void
Attributes
一个  TTY 流。
options:<Object>
autoCommit:<boolean>
如果为  true ,则无需调用 rl.commit() 。
M

rl.clearLine

History
rl.clearLine(dir): void
Attributes
-1:
:光标左侧
1:
:光标右侧
0:
:整行

rl.clearLine() 方法向内部待处理操作列表添加一个操作, 该操作按 dir 指定的方向清除关联 stream 的 当前行。 除非向构造函数传入了 autoCommit: true,否则调用 rl.commit() 才能看到此方法的效果。

M

rl.clearScreenDown

History
rl.clearScreenDown(): void
  • 返回: this

rl.clearScreenDown() 方法向内部待处理操作列表添加一个 操作,该操作从光标的当前位置向下清除 关联的流。 除非向构造函数传入了 autoCommit: true,否则调用 rl.commit() 才能看到此方法的效果。

M

rl.commit

History
rl.commit(): void

rl.commit() 方法将所有待处理操作发送到关联的 stream,并清除内部待处理操作列表。

M

rl.cursorTo

History
rl.cursorTo(x, y?): void
Attributes

rl.cursorTo() 方法向内部待处理操作列表添加一个操作, 该操作将光标移动到关联 stream 中的指定位置。 除非向构造函数传入了 autoCommit: true,否则调用 rl.commit() 才能看到此方法的效果。

M

rl.moveCursor

History
rl.moveCursor(dx, dy): void
Attributes

rl.moveCursor() 方法向内部待处理操作列表添加一个 操作,该操作将光标 相对 于其在关联 stream 中的 当前位置移动。 除非向构造函数传入了 autoCommit: true,否则调用 rl.commit() 才能看到此方法的效果。

M

rl.rollback

History
rl.rollback(): void
  • 返回: this

rl.rollback 方法清除内部待处理操作列表, 而不将其发送到关联的 stream。

M

readlinePromises.createInterface

History
readlinePromises.createInterface(options): void
Attributes
options:<Object>
要监听的  Readable 流。此选项 为 必填项 。
要写入 readline 数据的  Writable 流。
completer:<Function>
用于 Tab 自动补全的可选函数。
terminal:<boolean>
如果  input 和 output 流应 被视为 TTY,并向其写入 ANSI/VT100 转义码,则为 true 。 默认值: 实例化时检查 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 ,在这种情况下,后跟 \n 的 \r 将始终被视为单个换行符(这对于 使用 \r\n 行分隔符的 读取文件 可能是合理的)。 默认值: 100 。
escapeCodeTimeout:<number>
readlinePromises 等待某个字符的 时长(以毫秒为单位,当读取一个不明确的按键序列时, 该序列既可以基于目前读取的输入形成完整的按键序列, 也可以接受更多输入以完成更长的按键序列)。 默认值: 500 。
tabSize:<integer>
制表符等效的空格数(最小为 1)。  默认值: 8 。
允许使用 AbortSignal 关闭接口。

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

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

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

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

如果此实例的 terminal 为 true,则 output 流将 在定义 output.columns 属性并在列发生变化时 在 output 上触发 'resize' 事件时获得最佳兼容性 (当 process.stdout 是 TTY 时会自动这样做)。

completer 函数将用户当前输入的行 作为参数,并返回一个包含 2 个元素的 Array:

  • 一个包含匹配补全项的 Array。
  • 用于匹配的子字符串。

例如:[[substr1, substr2, ...], originalsubstring]。

function completer(line) {
  const completions = '.help .error .exit .quit .q'.split(' ');
  const hits = completions.filter((c) => c.startsWith(line));
  // 如果没有找到匹配项,则显示所有补全
  return [hits.length ? hits : completions, line];
}

completer 函数也可以返回 <Promise>,或者使用异步方式:

async function completer(linePartial) {
  await someAsyncWork();
  return [['123'], linePartial];
}

回调 API

History
class readline.Interface extends readline.InterfaceConstructor

readline.Interface 类的实例使用 readline.createInterface() 方法构造。每个实例都与一个 input Readable 流和一个 output Writable 流相关联。 output 流用于为到达的用户输入打印提示符, 并从 input 流中读取。

M

rl.question

History
rl.question(query, options?, callback): void
Attributes
query:<string>
要写入  output 的语句或查询, 位于提示符之前。
options:<Object>
可选地允许取消  question() , 方式是使用 AbortController 。
callback:<Function>
一个回调函数,使用用户的 输入来调用,以响应  query 。

rl.question() 方法通过将 query 写入 output 来显示它, 等待在 input 上提供用户输入,然后调用 callback 函数,并将提供的输入作为第一个参数传入。

调用时,如果 input 流已被 暂停,rl.question() 将恢复它。

如果创建 readline.Interface 时将 output 设置为 null 或 undefined,则不会写入 query。

传递给 rl.question() 的 callback 函数不遵循典型的 模式,即第一个参数是 Error 对象或 null。 调用 callback 时,提供的答案是唯一的参数。

如果在 rl.close() 之后调用 rl.question(),将抛出错误。

用法示例:

rl.question('What is your favorite food? ', (answer) => {
  console.log(`Oh, so your favorite food is ${answer}`);
});

使用 AbortController 取消提问。

const ac = new AbortController();
const signal = ac.signal;

rl.question('What is your favorite food? ', { signal }, (answer) => {
  console.log(`Oh, so your favorite food is ${answer}`);
});

signal.addEventListener('abort', () => {
  console.log('The food question timed out');
}, { once: true });

setTimeout(() => ac.abort(), 10000);
readline.clearLine(stream, dir, callback?): void
Attributes
-1:
:光标左侧
1:
:光标右侧
0:
:整行
callback:<Function>
操作完成后调用。

readline.clearLine() 方法清除给定 TTY 流的当前行, 方向由 dir 指定。

readline.clearScreenDown(stream, callback?): void
Attributes
callback:<Function>
操作完成后调用。

readline.clearScreenDown() 方法从 光标的当前位置向下清除给定的 TTY 流。

readline.createInterface(options): void
Attributes
options:<Object>
要监听的  可读流 。此选项 为 必需 。
用于写入 readline 数据的  可写流 所指向的目标。
completer:<Function>
用于 Tab 自动补全的可选函数。
terminal:<boolean>
如果  input 和 output 流应被视为 TTY,则为 true , 并向其写入 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 。
允许使用 AbortSignal 关闭接口。 中止该信号将在内部调用接口的  close 。

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

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

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

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

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

当使用 stdin 作为输入创建 readline.Interface 时,程序 在收到 EOF 字符 之前不会终止。若要不等待 用户输入就退出,请调用 process.stdin.unref()。

completer 函数接受用户输入的当前行 作为参数,并返回一个包含 2 个条目的 Array:

  • 包含匹配补全项的 Array。
  • 用于匹配的子字符串。

例如:[[substr1, substr2, ...], originalsubstring]。

function completer(line) {
  const completions = '.help .error .exit .quit .q'.split(' ');
  const hits = completions.filter((c) => c.startsWith(line));
  // 如果没有找到匹配项,则显示所有补全
  return [hits.length ? hits : completions, line];
}

如果 completer 函数接受两个 参数,则可以异步调用它:

function completer(linePartial, callback) {
  callback(null, [['123'], linePartial]);
}
readline.cursorTo(stream, x, y?, callback?): void
Attributes
callback:<Function>
操作完成后调用。

readline.cursorTo() 方法将光标移动到 给定 TTY stream 中的指定位置。

readline.moveCursor(stream, dx, dy, callback?): void
Attributes
callback:<Function>
操作完成后调用。

readline.moveCursor() 方法将光标 相对 于其在 给定 TTY stream 中的当前位置移动。

M

readline.emitKeypressEvents

History
readline.emitKeypressEvents(stream, interface?): void
Attributes

readline.emitKeypressEvents() 方法使给定的 可读流 开始发出与接收到的输入相对应的 'keypress' 事件。

可选地,interface 指定一个 readline.Interface 实例, 当检测到复制粘贴的输入时,将禁用该实例的自动补全。

如果 stream 是 TTY,则它必须处于原始模式。

如果 input 是终端,则任何 readline 实例都会在其 input 上 自动调用此方法。关闭 readline 实例并不会阻止 input 发出 'keypress' 事件。

readline.emitKeypressEvents(process.stdin);
if (process.stdin.isTTY)
  process.stdin.setRawMode(true);

以下示例说明如何使用 readline.Interface 类来 实现一个小型命令行界面:

import { createInterface } from 'node:readline';
import { exit, stdin, stdout } from 'node:process';
const rl = createInterface({
  input: stdin,
  output: stdout,
  prompt: 'OHAI> ',
});

rl.prompt();

rl.on('line', (line) => {
  switch (line.trim()) {
    case 'hello':
      console.log('world!');
      break;
    default:
      console.log(`Say what? I might have heard '${line.trim()}'`);
      break;
  }
  rl.prompt();
}).on('close', () => {
  console.log('Have a great day!');
  exit(0);
});

readline 的一个常见用例是逐行消费 输入文件。最简单的方法是利用 fs.ReadStream API 以及 for await...of 循环:

import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';

async function processLineByLine() {
  const fileStream = createReadStream('input.txt');

  const rl = createInterface({
    input: fileStream,
    crlfDelay: Infinity,
  });
  // 注意:我们使用 crlfDelay 选项将 input.txt 中所有 CR LF
  // ('\r\n') 实例识别为单个换行符。

  for await (const line of rl) {
    // input.txt 中的每一行都将在此处依次作为 `line` 可用。
    console.log(`Line from file: ${line}`);
  }
}

processLineByLine();

或者,也可以使用 'line' 事件:

import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';

const rl = createInterface({
  input: createReadStream('sample.txt'),
  crlfDelay: Infinity,
});

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

目前,for await...of 循环可能会稍慢一些。如果 async / await 流程和速度都很重要,可以采用混合方法:

import { once } from 'node:events';
import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';

(async function processLineByLine() {
  try {
    const rl = createInterface({
      input: createReadStream('big-file.txt'),
      crlfDelay: Infinity,
    });

    rl.on('line', (line) => {
      // 处理该行。
    });

    await once(rl, 'close');

    console.log('File processed.');
  } catch (err) {
    console.error(err);
  }
})();
键位绑定 描述 说明
Ctrl+Shift+Backspace 删除左侧行内容 在 Linux、Mac 和 Windows 上不起作用
Ctrl+Shift+Delete 删除右侧行内容 在 Mac 上不起作用
Ctrl+C 发出 SIGINT 或关闭 readline 实例
Ctrl+H 删除左侧字符
Ctrl+D 删除右侧字符;如果当前行为空或为 EOF,则关闭 readline 实例 在 Windows 上不起作用
Ctrl+U 从当前位置删除至行首
Ctrl+K 从当前位置删除至行尾
Ctrl+Y 粘贴(取回)之前删除的文本 仅适用于由 Ctrl+U 或 Ctrl+K 删除的文本
Meta+Y 在之前删除的文本之间循环切换 仅当上一次按键为 Ctrl+Y 或 Meta+Y 时可用
Ctrl+A 移至行首
Ctrl+E 移至行尾
Ctrl+B 后退一个字符
Ctrl+F 前进一个字符
Ctrl+L 清屏
Ctrl+N 下一个历史项
Ctrl+P 上一个历史项
Ctrl+- 撤销上一次更改 任何发出键码 0x1F 的按键都会执行此操作。 在许多终端(例如 xterm)中, 它被绑定到 Ctrl+-。
Ctrl+6 重做上一次更改 许多终端没有默认的重做按键。 我们选择键码 0x1E 来执行重做。 在 xterm 中,它绑定到 Ctrl+6 这是默认设置。
Ctrl+Z 将正在运行的进程移到后台。输入 fg 并按 Enter 以返回。 在 Windows 上不起作用
Ctrl+W 或 Ctrl +Backspace 向后删除至单词边界 Ctrl+Backspace 在 Linux、Mac 和 Windows 上不起作用
Ctrl+Delete 向前删除至单词边界 在 Mac 上不起作用
Ctrl+Left arrow 或 Meta+B 移至上一个单词 Ctrl+Left arrow 在 Mac 上不起作用
Ctrl+Right arrow 或 Meta+F 移至下一个单词 Ctrl+Right arrow 在 Mac 上不起作用
Meta+D 或 Meta +Delete 删除右侧单词 Meta+Delete 在 Windows 上不起作用
Meta+Backspace 删除左侧单词 在 Mac 上不起作用