自定义评估函数


【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.】

执行函数接受以下四个参数:

【An evaluation function accepts the following four arguments:】

  • code <string> 要执行的代码(例如 1 + 1)。
  • context <Object> 代码执行的上下文。这可以是 JavaScript 的 global 上下文,也可以是特定于 REPL 实例的上下文,这取决于 useGlobal 选项。
  • replResourceName <string> 与当前代码评估相关的 REPL 资源的标识符。这对于调试可能很有用。
  • callback <Function> 代码评估完成后调用的函数。回调函数接受两个参数:
    • 如果在评估过程中发生错误,则提供一个错误对象;如果没有发生错误,则为 nullundefined
    • 代码评估的结果(如果提供了错误,则此结果不相关)。

下面示例演示了一个 REPL,它可以对给定的数字进行平方计算,如果提供的输入实际上不是数字,则会打印错误信息:

【The following illustrates an example of a REPL that squares a given number, an error is instead printed if the provided input is not actually a number:】

import repl from 'node:repl';

function byThePowerOfTwo(number) {
  return number * number;
}

function myEval(code, context, replResourceName, callback) {
  if (isNaN(code)) {
    callback(new Error(`${code.trim()} is not a number`));
  } else {
    callback(null, byThePowerOfTwo(code));
  }
}

repl.start({ prompt: 'Enter a number: ', eval: myEval });const repl = require('node:repl');

function byThePowerOfTwo(number) {
  return number * number;
}

function myEval(code, context, replResourceName, callback) {
  if (isNaN(code)) {
    callback(new Error(`${code.trim()} is not a number`));
  } else {
    callback(null, byThePowerOfTwo(code));
  }
}

repl.start({ prompt: 'Enter a number: ', eval: myEval });