script.runInContext(contextifiedObject[, options])
contextifiedObject<Object>vm.createContext()方法返回的 情境化 对象。options<Object>- 返回:<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' } 使用 timeout 或 breakOnSigint 选项会导致启动新的事件循环和相应的线程,这会带来一定的性能开销。
🌐 Using the timeout or breakOnSigint options will result in new event loops
and corresponding threads being started, which have a non-zero performance
overhead.