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.