script.runInThisContext([options])
在当前 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