script.runInContext(contextifiedObject[, options])


  • contextifiedObject <Object> 一个 情境化 对象,由 vm.createContext() 方法返回。
  • options <Object>
    • displayErrors <boolean> 当设置为 true 时,如果在编译 code 时发生 Error,导致错误的代码行会附加到堆栈跟踪中。默认值: true
    • timeout <integer> 指定执行 code 前的毫秒数,超过此时间将终止执行。如果执行被终止,将抛出一个 Error。此值必须是严格正整数。
    • breakOnSigint <boolean> 如果为 true,接收到 SIGINTCtrl+C)将终止执行并抛出一个 Error。在脚本执行期间,通过 process.on('SIGINT') 附加的现有事件处理程序将被禁用,但在脚本执行后仍然继续工作。默认值: false
  • 返回:<any> 脚本中最后执行的语句的结果。

在给定的 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.】