Node.js v22.11.0 文档


REPL#

稳定性: 2 - 稳定的

¥Stability: 2 - Stable

源代码: lib/repl.js

node:repl 模块提供了一个读取-评估-打印-循环 (REPL) 实现,它既可以作为独立程序使用,也可以包含在其他应用中。可以使用以下方式访问它:

¥The node:repl module provides a Read-Eval-Print-Loop (REPL) implementation that is available both as a standalone program or includible in other applications. It can be accessed using:

const repl = require('node:repl'); 

设计和特点#

¥Design and features

node:repl 模块导出 repl.REPLServer 类。当运行时,repl.REPLServer 的实例将接受用户输入的单行,根据用户定义的评估函数评估它们,然后输出结果。输入和输出可能分别来自 stdinstdout,或者可能连接到任何 Node.js

¥The node:repl module exports the repl.REPLServer class. While running, instances of repl.REPLServer will accept individual lines of user input, evaluate those according to a user-defined evaluation function, then output the result. Input and output may be from stdin and stdout, respectively, or may be connected to any Node.js stream.

repl.REPLServer 实例支持输入自动补全、补全预览、极简 Emacs 风格行编辑、多行输入、ZSH 类 reverse-i-search、ZSH 类子串历史搜索、ANSI 风格输出、保存和恢复 当前 REPL 会话状态、错误恢复和可定制的评估功能。不支持 ANSI 风格和 Emacs 风格的行编辑的终端会自动回退到有限的功能集。

¥Instances of repl.REPLServer support automatic completion of inputs, completion preview, simplistic Emacs-style line editing, multi-line inputs, ZSH-like reverse-i-search, ZSH-like substring-based history search, ANSI-styled output, saving and restoring current REPL session state, error recovery, and customizable evaluation functions. Terminals that do not support ANSI styles and Emacs-style line editing automatically fall back to a limited feature set.

命令和特殊键#

¥Commands and special keys

所有 REPL 实例都支持以下特殊命令:

¥The following special commands are supported by all REPL instances:

  • .break:在输入多行表达式的过程中,输入 .break 命令(或按 Ctrl+C)可中止对该表达式的进一步输入或处理。

    ¥.break: When in the process of inputting a multi-line expression, enter the .break command (or press Ctrl+C) to abort further input or processing of that expression.

  • .clear:将 REPL context 重置为空对象并清除任何输入的多行表达式。

    ¥.clear: Resets the REPL context to an empty object and clears any multi-line expression being input.

  • .exit:关闭 I/O 流,导致 REPL 退出。

    ¥.exit: Close the I/O stream, causing the REPL to exit.

  • .help:显示此特殊命令列表。

    ¥.help: Show this list of special commands.

  • .save:将当前 REPL 会话保存到一个文件中:> .save ./file/to/save.js

    ¥.save: Save the current REPL session to a file: > .save ./file/to/save.js

  • .load:将文件加载到当前 REPL 会话中。> .load ./file/to/load.js

    ¥.load: Load a file into the current REPL session. > .load ./file/to/load.js

  • .editor:进入编辑模式(Ctrl+D 完成,Ctrl+C 取消)。

    ¥.editor: Enter editor mode (Ctrl+D to finish, Ctrl+C to cancel).

> .editor
// Entering editor mode (^D to finish, ^C to cancel)
function welcome(name) {
  return `Hello ${name}!`;
}

welcome('Node.js User');

// ^D
'Hello Node.js User!'
> 

REPL 中的以下组合键具有这些特殊效果:

¥The following key combinations in the REPL have these special effects:

  • Ctrl+C:按一次时,与 .break 命令具有相同的效果。当在空白行上按两次时,效果与 .exit 命令相同。

    ¥Ctrl+C: When pressed once, has the same effect as the .break command. When pressed twice on a blank line, has the same effect as the .exit command.

  • Ctrl+D:与 .exit 命令具有相同的效果。

    ¥Ctrl+D: Has the same effect as the .exit command.

  • Tab:在空白行上按下时,显示全局和局部(作用域)变量。当在输入其他输入时按下时,显示相关的自动补齐选项。

    ¥Tab: When pressed on a blank line, displays global and local (scope) variables. When pressed while entering other input, displays relevant autocompletion options.

有关反向搜索的键绑定,请参阅 reverse-i-search。对于所有其他键绑定,请参阅 TTY 键绑定

¥For key bindings related to the reverse-i-search, see reverse-i-search. For all other key bindings, see TTY keybindings.

默认评估#

¥Default evaluation

默认情况下,repl.REPLServer 的所有实例都使用评估函数来评估 JavaScript 表达式并提供对 Node.js 内置模块的访问。可以通过在创建 repl.REPLServer 实例时传入替代评估函数来覆盖此默认行为。

¥By default, all instances of repl.REPLServer use an evaluation function that evaluates JavaScript expressions and provides access to Node.js built-in modules. This default behavior can be overridden by passing in an alternative evaluation function when the repl.REPLServer instance is created.

JavaScript 表达式#

¥JavaScript expressions

默认的求值器支持 JavaScript 表达式的直接求值:

¥The default evaluator supports direct evaluation of JavaScript expressions:

> 1 + 1
2
> const m = 2
undefined
> m + 1
3 

除非在块或函数内另有作用域,否则隐式声明或使用 constletvar 关键字声明的变量在全局作用域内声明。

¥Unless otherwise scoped within blocks or functions, variables declared either implicitly or using the const, let, or var keywords are declared at the global scope.

全局和本地作用域#

¥Global and local scope

默认求值器提供对全局作用域中存在的任何变量的访问。可以通过将变量分配给与每个 REPLServer 关联的 context 对象来显式地向 REPL 公开变量:

¥The default evaluator provides access to any variables that exist in the global scope. It is possible to expose a variable to the REPL explicitly by assigning it to the context object associated with each REPLServer:

const repl = require('node:repl');
const msg = 'message';

repl.start('> ').context.m = msg; 

context 对象中的属性在 REPL 中显示为本地:

¥Properties in the context object appear as local within the REPL:

$ node repl_test.js
> m
'message' 

默认情况下上下文属性不是只读的。要指定只读的全局变量,则必须使用 Object.defineProperty() 定义上下文属性:

¥Context properties are not read-only by default. To specify read-only globals, context properties must be defined using Object.defineProperty():

const repl = require('node:repl');
const msg = 'message';

const r = repl.start('> ');
Object.defineProperty(r.context, 'm', {
  configurable: false,
  enumerable: true,
  value: msg,
}); 

访问核心 Node.js 模块#

¥Accessing core Node.js modules

默认的求值器会在使用时自动将 Node.js 核心模块加载到 REPL 环境中。例如,除非另外声明为全局变量或作用域变量,否则输入 fs 将按需评估为 global.fs = require('node:fs')

¥The default evaluator will automatically load Node.js core modules into the REPL environment when used. For instance, unless otherwise declared as a global or scoped variable, the input fs will be evaluated on-demand as global.fs = require('node:fs').

> fs.createReadStream('./some/file'); 

全局未捕获异常#

¥Global uncaught exceptions

REPL 使用 domain 模块来捕获该 REPL 会话的所有未捕获的异常。

¥The REPL uses the domain module to catch all uncaught exceptions for that REPL session.

在 REPL 中使用 domain 模块有这些副作用:

¥This use of the domain module in the REPL has these side effects:

_(下划线)变量的赋值#

¥Assignment of the _ (underscore) variable

默认情况下,默认求值器会将最近求值的表达式的结果分配给特殊变量 _(下划线)。将 _ 显式设置为一个值将禁用此行为。

¥The default evaluator will, by default, assign the result of the most recently evaluated expression to the special variable _ (underscore). Explicitly setting _ to a value will disable this behavior.

> [ 'a', 'b', 'c' ]
[ 'a', 'b', 'c' ]
> _.length
3
> _ += 1
Expression assignment to _ now disabled.
4
> 1 + 1
2
> _
4 

同样,_error 将引用上次看到的错误,如果有的话。将 _error 显式设置为一个值将禁用此行为。

¥Similarly, _error will refer to the last seen error, if there was any. Explicitly setting _error to a value will disable this behavior.

> throw new Error('foo');
Uncaught Error: foo
> _error.message
'foo' 

await 关键词#

¥await keyword

在顶层启用对 await 关键字的支持。

¥Support for the await keyword is enabled at the top level.

> await Promise.resolve(123)
123
> await Promise.reject(new Error('REPL await'))
Uncaught Error: REPL await
    at REPL2:1:54
> const timeout = util.promisify(setTimeout);
undefined
> const old = Date.now(); await timeout(1000); console.log(Date.now() - old);
1002
undefined 

在 REPL 中使用 await 关键字的一个已知限制是它会使 constlet 关键字的词法范围无效。

¥One known limitation of using the await keyword in the REPL is that it will invalidate the lexical scoping of the const and let keywords.

例如:

¥For example:

> const m = await Promise.resolve(123)
undefined
> m
123
> const m = await Promise.resolve(234)
undefined
> m
234 

--no-experimental-repl-await 应禁用 REPL 中的顶层等待。

¥--no-experimental-repl-await shall disable top-level await in REPL.

反向搜索#

¥Reverse-i-search

REPL 支持类似于 ZSH 的双向反向搜索。向后搜索由 Ctrl+R 触发,向前搜索由 Ctrl+S 触发。

¥The REPL supports bi-directional reverse-i-search similar to ZSH. It is triggered with Ctrl+R to search backward and Ctrl+S to search forwards.

重复的历史条目将被跳过。

¥Duplicated history entries will be skipped.

只要按下与反向搜索不对应的任何键,条目就会被接受。按 EscCtrl+C 可以取消。

¥Entries are accepted as soon as any key is pressed that doesn't correspond with the reverse search. Cancelling is possible by pressing Esc or Ctrl+C.

改变方向立即从当前位置开始搜索预期方向的下一个条目。

¥Changing the direction immediately searches for the next entry in the expected direction from the current position on.

自定义评估函数#

¥Custom evaluation functions

当新建 repl.REPLServer 时,可能会提供自定义评价函数。例如,这可用于实现完全定制的 REPL 应用。

¥When a new repl.REPLServer is created, a custom evaluation function may be provided. This can be used, for instance, to implement fully customized REPL applications.

以下说明了一个 REPL 的假设示例,该示例执行将文本从一种语言翻译成另一种语言:

¥The following illustrates a hypothetical example of a REPL that performs translation of text from one language to another:

const repl = require('node:repl');
const { Translator } = require('translator');

const myTranslator = new Translator('en', 'fr');

function myEval(cmd, context, filename, callback) {
  callback(null, myTranslator.translate(cmd));
}

repl.start({ prompt: '> ', eval: myEval }); 

可恢复的错误#

¥Recoverable errors

在 REPL 提示符下,按 Enter 将当前输入行发送到 eval 函数。为了支持多行输入,eval 函数可以返回 repl.Recoverable 的实例给提供的回调函数:

¥At the REPL prompt, pressing Enter sends the current line of input to the eval function. In order to support multi-line input, the eval function can return an instance of repl.Recoverable to the provided callback function:

function myEval(cmd, context, filename, callback) {
  let result;
  try {
    result = vm.runInThisContext(cmd);
  } catch (e) {
    if (isRecoverableError(e)) {
      return callback(new repl.Recoverable(e));
    }
  }
  callback(null, result);
}

function isRecoverableError(error) {
  if (error.name === 'SyntaxError') {
    return /^(Unexpected end of input|Unexpected token)/.test(error.message);
  }
  return false;
} 

自定义 REPL 输出#

¥Customizing REPL output

默认情况下,repl.REPLServer 实例在将输出写入提供的 Writable 流(默认为 process.stdout)之前使用 util.inspect() 方法格式化输出。showProxy 检查选项默认设置为 true,colors 选项设置为 true,具体取决于 REPL 的 useColors 选项。

¥By default, repl.REPLServer instances format output using the util.inspect() method before writing the output to the provided Writable stream (process.stdout by default). The showProxy inspection option is set to true by default and the colors option is set to true depending on the REPL's useColors option.

可以在构造时指定 useColors 布尔选项,以指示默认编写器使用 ANSI 风格的代码为 util.inspect() 方法的输出着色。

¥The useColors boolean option can be specified at construction to instruct the default writer to use ANSI style codes to colorize the output from the util.inspect() method.

如果 REPL 作为独立程序运行,也可以通过使用从 util.inspect() 镜像 defaultOptionsinspect.replDefaults 属性从 REPL 内部更改 REPL 的 检查默认值

¥If the REPL is run as standalone program, it is also possible to change the REPL's inspection defaults from inside the REPL by using the inspect.replDefaults property which mirrors the defaultOptions from util.inspect().

> util.inspect.replDefaults.compact = false;
false
> [1]
[
  1
]
> 

要完全自定义 repl.REPLServer 实例的输出,则在构建时为 writer 选项传入新函数。例如,下面的示例只是将任何输入文本转换为大写:

¥To fully customize the output of a repl.REPLServer instance pass in a new function for the writer option on construction. The following example, for instance, simply converts any input text to upper case:

const repl = require('node:repl');

const r = repl.start({ prompt: '> ', eval: myEval, writer: myWriter });

function myEval(cmd, context, filename, callback) {
  callback(null, cmd);
}

function myWriter(output) {
  return output.toUpperCase();
} 

类:REPLServer#

¥Class: REPLServer

repl.REPLServer 的实例是使用 repl.start() 方法或直接使用 JavaScript new 关键字创建的。

¥Instances of repl.REPLServer are created using the repl.start() method or directly using the JavaScript new keyword.

const repl = require('node:repl');

const options = { useColors: true };

const firstInstance = repl.start(options);
const secondInstance = new repl.REPLServer(options); 

事件:'exit'#

¥Event: 'exit'

当通过接收 .exit 命令作为输入、用户按 Ctrl+C 两次以触发 SIGINT 信号或通过按 Ctrl+D 以在输入流上触发 'end' 信号退出 REPL 时,会触发 'exit' 事件。不带任何参数调用监听器回调。

¥The 'exit' event is emitted when the REPL is exited either by receiving the .exit command as input, the user pressing Ctrl+C twice to signal SIGINT, or by pressing Ctrl+D to signal 'end' on the input stream. The listener callback is invoked without any arguments.

replServer.on('exit', () => {
  console.log('Received "exit" event from repl!');
  process.exit();
}); 

事件:'reset'#

¥Event: 'reset'

当重置 REPL 的上下文时会触发 'reset' 事件。只要接收到 .clear 命令作为输入,就会发生这种情况,除非 REPL 使用默认计算器并且 repl.REPLServer 实例是在 useGlobal 选项设置为 true 的情况下创建的。将使用对 context 对象的引用作为唯一参数调用监听器回调。

¥The 'reset' event is emitted when the REPL's context is reset. This occurs whenever the .clear command is received as input unless the REPL is using the default evaluator and the repl.REPLServer instance was created with the useGlobal option set to true. The listener callback will be called with a reference to the context object as the only argument.

这可以主要用于将 REPL 上下文重新初始化为一些预定义的状态:

¥This can be used primarily to re-initialize REPL context to some pre-defined state:

const repl = require('node:repl');

function initializeContext(context) {
  context.m = 'test';
}

const r = repl.start({ prompt: '> ' });
initializeContext(r.context);

r.on('reset', initializeContext); 

当执行此代码时,可以修改全局 'm' 变量,然后使用 .clear 命令将其重置为其初始值:

¥When this code is executed, the global 'm' variable can be modified but then reset to its initial value using the .clear command:

$ ./node example.js
> m
'test'
> m = 1
1
> m
1
> .clear
Clearing context...
> m
'test'
> 

replServer.defineCommand(keyword, cmd)#

  • keyword <string> 命令关键字(没有前导 . 字符)。

    ¥keyword <string> The command keyword (without a leading . character).

  • cmd <Object> | <Function> 当处理命令时调用的函数。

    ¥cmd <Object> | <Function> The function to invoke when the command is processed.

replServer.defineCommand() 方法用于向 REPL 实例添加新的以 . 为前缀的命令。此类命令是通过键入 . 后跟 keyword 来调用的。cmd 是具有以下属性的 FunctionObject

¥The replServer.defineCommand() method is used to add new .-prefixed commands to the REPL instance. Such commands are invoked by typing a . followed by the keyword. The cmd is either a Function or an Object with the following properties:

  • help <string> 当输入 .help 时显示的帮助文本(可选)。

    ¥help <string> Help text to be displayed when .help is entered (Optional).

  • action <Function> 要执行的函数,可选择接受单个字符串参数。

    ¥action <Function> The function to execute, optionally accepting a single string argument.

以下示例显示了添加到 REPL 实例的两个新命令:

¥The following example shows two new commands added to the REPL instance:

const repl = require('node:repl');

const replServer = repl.start({ prompt: '> ' });
replServer.defineCommand('sayhello', {
  help: 'Say hello',
  action(name) {
    this.clearBufferedCommand();
    console.log(`Hello, ${name}!`);
    this.displayPrompt();
  },
});
replServer.defineCommand('saybye', function saybye() {
  console.log('Goodbye!');
  this.close();
}); 

然后可以在 REPL 实例中使用新命令:

¥The new commands can then be used from within the REPL instance:

> .sayhello Node.js User
Hello, Node.js User!
> .saybye
Goodbye! 

replServer.displayPrompt([preserveCursor])#

replServer.displayPrompt() 方法准备 REPL 实例以供用户输入,将配置的 prompt 打印到 output 中的新行并恢复 input 以接受新输入。

¥The replServer.displayPrompt() method readies the REPL instance for input from the user, printing the configured prompt to a new line in the output and resuming the input to accept new input.

输入多行输入时,会打印省略号而不是 'prompt'。

¥When multi-line input is being entered, an ellipsis is printed rather than the 'prompt'.

preserveCursortrue 时,光标位置不会重置为 0

¥When preserveCursor is true, the cursor placement will not be reset to 0.

replServer.displayPrompt 方法主要用于从操作函数内部调用使用 replServer.defineCommand() 方法注册的命令。

¥The replServer.displayPrompt method is primarily intended to be called from within the action function for commands registered using the replServer.defineCommand() method.

replServer.clearBufferedCommand()#

replServer.clearBufferedCommand() 方法清除任何已缓冲但尚未执行的命令。此方法主要用于从使用 replServer.defineCommand() 方法注册的命令的操作函数中调用。

¥The replServer.clearBufferedCommand() method clears any command that has been buffered but not yet executed. This method is primarily intended to be called from within the action function for commands registered using the replServer.defineCommand() method.

replServer.setupHistory(historyPath, callback)#

初始化 REPL 实例的历史日志文件。当执行 Node.js 二进制文件并使用命令行 REPL 时,默认情况下会初始化一个历史文件。但是,以编程方式创建 REPL 时并非如此。在以编程方式使用 REPL 实例时,使用此方法初始化历史日志文件。

¥Initializes a history log file for the REPL instance. When executing the Node.js binary and using the command-line REPL, a history file is initialized by default. However, this is not the case when creating a REPL programmatically. Use this method to initialize a history log file when working with REPL instances programmatically.

repl.builtinModules#

所有 Node.js 模块的名称列表,例如 'http'

¥A list of the names of all Node.js modules, e.g., 'http'.

repl.start([options])#

  • options <Object> | <string>

    • prompt <string> 要显示的输入提示。默认值:'> '(尾随空格)。

      ¥prompt <string> The input prompt to display. Default: '> ' (with a trailing space).

    • input <stream.Readable> 将从中读取 REPL 输入的 Readable 流。默认值:process.stdin

      ¥input <stream.Readable> The Readable stream from which REPL input will be read. Default: process.stdin.

    • output <stream.Writable> REPL 输出将写入的 Writable 流。默认值:process.stdout

      ¥output <stream.Writable> The Writable stream to which REPL output will be written. Default: process.stdout.

    • terminal <boolean> 如果 true,则指定 output 应被视为 TTY 终端。默认值:在实例化时检查 output 流上 isTTY 属性的值。

      ¥terminal <boolean> If true, specifies that the output should be treated as a TTY terminal. Default: checking the value of the isTTY property on the output stream upon instantiation.

    • eval <Function> 当评估每一给定输入行时要使用的函数。默认值:JavaScript eval() 函数的异步封装器。eval 函数可能会出现 repl.Recoverable 错误,表明输入不完整并提示输入额外的行。

      ¥eval <Function> The function to be used when evaluating each given line of input. Default: an async wrapper for the JavaScript eval() function. An eval function can error with repl.Recoverable to indicate the input was incomplete and prompt for additional lines.

    • useColors <boolean> 如果为 true,则指定默认的 writer 函数应在 REPL 输出中包含 ANSI 颜色样式。如果提供了自定义 writer 函数,则此功能无效。默认值:如果 REPL 实例的 terminal 值为 true,则检查 output 流上的颜色支持。

      ¥useColors <boolean> If true, specifies that the default writer function should include ANSI color styling to REPL output. If a custom writer function is provided then this has no effect. Default: checking color support on the output stream if the REPL instance's terminal value is true.

    • useGlobal <boolean> 如果为 true,则指定默认评估函数将使用 JavaScript global 作为上下文,而不是为 REPL 实例创建新的单独上下文。node CLI REPL 将此值设置为 true。默认值:false

      ¥useGlobal <boolean> If true, specifies that the default evaluation function will use the JavaScript global as the context as opposed to creating a new separate context for the REPL instance. The node CLI REPL sets this value to true. Default: false.

    • ignoreUndefined <boolean> 如果为 true,则指定默认编写器在计算结果为 undefined 时不会输出命令的返回值。默认值:false

      ¥ignoreUndefined <boolean> If true, specifies that the default writer will not output the return value of a command if it evaluates to undefined. Default: false.

    • writer <Function> 在写入 output 之前调用以格式化每个命令的输出的函数。默认值:util.inspect()

      ¥writer <Function> The function to invoke to format the output of each command before writing to output. Default: util.inspect().

    • completer <Function> 用于自定义 Tab 自动补齐的可选函数。有关示例,请参见 readline.InterfaceCompleter

      ¥completer <Function> An optional function used for custom Tab auto completion. See readline.InterfaceCompleter for an example.

    • replMode <symbol> 指定默认求值器是在严格模式还是默认(宽松)模式下执行所有 JavaScript 命令的标志。可接受的值是:

      ¥replMode <symbol> A flag that specifies whether the default evaluator executes all JavaScript commands in strict mode or default (sloppy) mode. Acceptable values are:

      • repl.REPL_MODE_SLOPPY 在宽松模式下计算表达式。

        ¥repl.REPL_MODE_SLOPPY to evaluate expressions in sloppy mode.

      • repl.REPL_MODE_STRICT 在严格模式下计算表达式。这相当于在每个 repl 语句前面加上 'use strict'

        ¥repl.REPL_MODE_STRICT to evaluate expressions in strict mode. This is equivalent to prefacing every repl statement with 'use strict'.

    • breakEvalOnSigint <boolean> 当收到 SIGINT 时,例如按下 Ctrl+C 时,停止评估当前代码段。这不能与自定义 eval 函数一起使用。默认值:false

      ¥breakEvalOnSigint <boolean> Stop evaluating the current piece of code when SIGINT is received, such as when Ctrl+C is pressed. This cannot be used together with a custom eval function. Default: false.

    • preview <boolean> 定义 repl 是否打印自动补齐和输出预览。默认值:true 使用默认 eval 函数,false 如果使用自定义 eval 函数。如果 terminal 为假,则没有预览,preview 的值没有影响。

      ¥preview <boolean> Defines if the repl prints autocomplete and output previews or not. Default: true with the default eval function and false in case a custom eval function is used. If terminal is falsy, then there are no previews and the value of preview has no effect.

  • 返回:<repl.REPLServer>

    ¥Returns: <repl.REPLServer>

repl.start() 方法创建并启动了一个 repl.REPLServer 实例。

¥The repl.start() method creates and starts a repl.REPLServer instance.

如果 options 是字符串,则指定输入提示:

¥If options is a string, then it specifies the input prompt:

const repl = require('node:repl');

// a Unix style prompt
repl.start('$ '); 

Node.js REPL#

Node.js 本身使用 node:repl 模块来提供自己的交互界面来执行 JavaScript。这可以通过执行 Node.js 二进制文件而不传入任何参数(或通过传入 -i 参数)来使用:

¥Node.js itself uses the node:repl module to provide its own interactive interface for executing JavaScript. This can be used by executing the Node.js binary without passing any arguments (or by passing the -i argument):

$ node
> const a = [1, 2, 3];
undefined
> a
[ 1, 2, 3 ]
> a.forEach((v) => {
...   console.log(v);
...   });
1
2
3 

环境变量选项#

¥Environment variable options

可以使用以下环境变量自定义 Node.js REPL 的各种行为:

¥Various behaviors of the Node.js REPL can be customized using the following environment variables:

  • NODE_REPL_HISTORY:当给出有效路径时,持久的 REPL 历史记录将保存到用户主目录中的指定文件而不是 .node_repl_history。将此值设置为 ''(空字符串)将禁用持久的 REPL 历史记录。将从值中删除空格。在 Windows 平台上,具有空值的环境变量无效,因此将此变量设置为一个或多个空格以禁用持久的 REPL 历史记录。

    ¥NODE_REPL_HISTORY: When a valid path is given, persistent REPL history will be saved to the specified file rather than .node_repl_history in the user's home directory. Setting this value to '' (an empty string) will disable persistent REPL history. Whitespace will be trimmed from the value. On Windows platforms environment variables with empty values are invalid so set this variable to one or more spaces to disable persistent REPL history.

  • NODE_REPL_HISTORY_SIZE:如果历史记录可用,则控制将保留多少行历史记录。必须是正数。默认值:1000

    ¥NODE_REPL_HISTORY_SIZE: Controls how many lines of history will be persisted if history is available. Must be a positive number. Default: 1000.

  • NODE_REPL_MODE:可能是 'sloppy''strict'。默认值:'sloppy',这将允许运行非严格模式代码。

    ¥NODE_REPL_MODE: May be either 'sloppy' or 'strict'. Default: 'sloppy', which will allow non-strict mode code to be run.

持久的历史记录#

¥Persistent history

默认情况下,Node.js REPL 将通过将输入保存到位于用户主目录中的 .node_repl_history 文件来保留 node REPL 会话之间的历史记录。这可以通过设置环境变量 NODE_REPL_HISTORY='' 来禁用。

¥By default, the Node.js REPL will persist history between node REPL sessions by saving inputs to a .node_repl_history file located in the user's home directory. This can be disabled by setting the environment variable NODE_REPL_HISTORY=''.

将 Node.js REPL 与高级行编辑器一起使用#

¥Using the Node.js REPL with advanced line-editors

对于高级行编辑器,使用环境变量 NODE_NO_READLINE=1 启动 Node.js。这将在规范的终端设置中启动主程序和调试器 REPL,这将允许与 rlwrap 一起使用。

¥For advanced line-editors, start Node.js with the environment variable NODE_NO_READLINE=1. This will start the main and debugger REPL in canonical terminal settings, which will allow use with rlwrap.

例如,可以将以下内容添加到 .bashrc 文件中:

¥For example, the following can be added to a .bashrc file:

alias node="env NODE_NO_READLINE=1 rlwrap node" 

针对单个正在运行的实例启动多个 REPL 实例#

¥Starting multiple REPL instances against a single running instance

可以针对共享单个 global 对象但具有单独 I/O 接口的单个​​运行 Node.js 实例创建和运行多个 REPL 实例。

¥It is possible to create and run multiple REPL instances against a single running instance of Node.js that share a single global object but have separate I/O interfaces.

例如,以下示例在 stdin、Unix 套接字和 TCP 套接字上提供单独的 REPL:

¥The following example, for instance, provides separate REPLs on stdin, a Unix socket, and a TCP socket:

const net = require('node:net');
const repl = require('node:repl');
let connections = 0;

repl.start({
  prompt: 'Node.js via stdin> ',
  input: process.stdin,
  output: process.stdout,
});

net.createServer((socket) => {
  connections += 1;
  repl.start({
    prompt: 'Node.js via Unix socket> ',
    input: socket,
    output: socket,
  }).on('exit', () => {
    socket.end();
  });
}).listen('/tmp/node-repl-sock');

net.createServer((socket) => {
  connections += 1;
  repl.start({
    prompt: 'Node.js via TCP socket> ',
    input: socket,
    output: socket,
  }).on('exit', () => {
    socket.end();
  });
}).listen(5001); 

从命令行运行此应用将在标准输入上启动 REPL。其他 REPL 客户端可以通过 Unix 套接字或 TCP 套接字连接。例如,telnet 可用于连接 TCP 套接字,而 socat 可用于连接 Unix 和 TCP 套接字。

¥Running this application from the command line will start a REPL on stdin. Other REPL clients may connect through the Unix socket or TCP socket. telnet, for instance, is useful for connecting to TCP sockets, while socat can be used to connect to both Unix and TCP sockets.

通过从基于 Unix 套接字的服务器而不是标准输入启动 REPL,可以连接到长时间运行的 Node.js 进程而无需重新启动它。

¥By starting a REPL from a Unix socket-based server instead of stdin, it is possible to connect to a long-running Node.js process without restarting it.

有关在 net.Servernet.Socket 实例上运行 "full-featured" (terminal) REPL 的示例,请参阅:https://gist.github.com/TooTallNate/2209310

¥For an example of running a "full-featured" (terminal) REPL over a net.Server and net.Socket instance, see: https://gist.github.com/TooTallNate/2209310.

有关在 curl(1) 上运行 REPL 实例的示例,请参阅:https://gist.github.com/TooTallNate/2053342

¥For an example of running a REPL instance over curl(1), see: https://gist.github.com/TooTallNate/2053342.

此示例仅用于教育目的,以演示如何使用不同的 I/O 流启动 Node.js REPL。它不应在生产环境或任何需要安全性的环境中使用,除非采取额外的保护措施。如果你需要在实际应用中实现 REPL,请考虑减轻这些风险的替代方法,例如使用安全输入机制和避免开放网络接口。

¥This example is intended purely for educational purposes to demonstrate how Node.js REPLs can be started using different I/O streams. It should not be used in production environments or any context where security is a concern without additional protective measures. If you need to implement REPLs in a real-world application, consider alternative approaches that mitigate these risks, such as using secure input mechanisms and avoiding open network interfaces.

Node.js 中文网 - 粤ICP备13048890号