script.runInThisContext([options])


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

在当前 global 对象的上下文中运行 vm.Script 所包含的已编译代码。运行的代码无法访问局部作用域,但 可以 访问当前的 global 对象。

【Runs the compiled code contained by the vm.Script within the context of the current global object. Running code does not have access to local scope, but does have access to the current global object.】

以下示例编译了一个递增 global 变量的代码,然后多次执行该代码:

【The following example compiles code that increments a global variable then executes that code multiple times:】

const vm = require('node:vm');

global.globalVar = 0;

const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });

for (let i = 0; i < 1000; ++i) {
  script.runInThisContext();
}

console.log(globalVar);

// 1000