自定义评估函数
¥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
)。¥
code
<string> The code to be executed (e.g.1 + 1
). -
context
<Object> 执行代码的上下文。这可以是 JavaScriptglobal
上下文,也可以是特定于 REPL 实例的上下文,具体取决于useGlobal
选项。¥
context
<Object> The context in which the code is executed. This can either be the JavaScriptglobal
context or a context specific to the REPL instance, depending on theuseGlobal
option. -
replResourceName
<string> 与当前代码执行关联的 REPL 资源的标识符。这对于调试目的很有用。¥
replResourceName
<string> An identifier for the REPL resource associated with the current code evaluation. This can be useful for debugging purposes. -
callback
<Function> 代码执行完成后调用的函数。回调函数接受两个参数:¥
callback
<Function> A function to invoke once the code evaluation is complete. The callback takes two parameters:-
执行过程中发生错误时提供的错误对象;未发生错误时提供
null
/undefined
。¥An error object to provide if an error occurred during evaluation, or
null
/undefined
if no error occurred. -
代码评估的结果(如果提供错误,则此结果无关)。
¥The result of the code evaluation (this is not relevant if an error is provided).
-
以下示例展示了一个 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 });