script.runInContext(contextifiedObject[, options])


版本历史
版本变更
v6.3.0

现在支持 breakOnSigint 选项。

v0.3.1

新增于: v0.3.1

  • contextifiedObject <Object> vm.createContext() 方法返回的 contextified 对象。

    \contextifiedObject <Object> A contextified object as returned by the vm.createContext() method.

  • options <Object>

    • displayErrors <boolean> 当为 true 时,如果编译 code 时出现 Error,则导致错误的代码行会附加到堆栈跟踪中。默认值:true

      \displayErrors <boolean> When true, if an Error occurs while compiling the code, the line of code causing the error is attached to the stack trace. Default: true.

    • timeout <integer> 指定终止执行前执行 code 的毫秒数。如果执行终止,则将抛出 Error。此值必须是严格的正整数。

      \timeout <integer> Specifies the number of milliseconds to execute code before terminating execution. If execution is terminated, an Error will be thrown. This value must be a strictly positive integer.

    • breakOnSigint <boolean> 如果是 true,接收 SIGINT(Ctrl+C)将终止执行并抛出 Error。已通过 process.on('SIGINT') 附加的事件的现有句柄在脚本执行期间被禁用,但在此之后继续工作。默认值:false

      \breakOnSigint <boolean> If true, receiving SIGINT (Ctrl+C) will terminate execution and throw an Error. Existing handlers for the event that have been attached via process.on('SIGINT') are disabled during script execution, but continue to work after that. Default: false.

  • 返回:<any> 脚本中最后一条语句执行的结果。

    \Returns: <any> the result of the very last statement executed in the script.

在给定的 contextifiedObject 中运行 vm.Script 对象包含的编译代码并返回结果。运行代码无权访问本地作用域。

\Runs the compiled code contained by the vm.Script object within the given contextifiedObject and returns the result. Running code does not have access to local scope.

下面的示例编译代码,增加一个全局变量,设置另一个全局变量的值,然后多次执行代码。全局变量包含在 context 对象中。

\The following example compiles code that increments a global variable, sets the value of another global variable, then execute the code multiple times. The globals are contained in the context object.

const vm = require('node:vm');
const context = {
 animal: 'cat',
 count: 2,
};
const script = new vm.Script('count += 1; name = "kitty";');
vm.createContext(context);
for (let i = 0; i < 10; ++i) {
 script.runInContext(context);
}
console.log(context);
// Prints: { animal: 'cat', count: 12, name: 'kitty' } 

使用 timeoutbreakOnSigint 选项将导致新的事件循环和相应的线程被启动,其性能开销非零。

\Using the timeout or breakOnSigint options will result in new event loops and corresponding threads being started, which have a non-zero performance overhead.

AltStyle によって変換されたページ (->オリジナル) /