script.runInContext(contextifiedObject[, options])
contextifiedObject
<Object>vm.createContext()
方法返回的上下文隔离化的对象。options
<Object>- 返回: <any> 脚本中执行的最后一条语句的结果。
在给定的 contextifiedObject
中运行 vm.Script
对象包含的编译代码并返回结果。
运行代码无权访问本地作用域。
下面的示例编译代码,增加一个全局变量,设置另一个全局变量的值,然后多次执行代码。
全局变量包含在 context
对象中。
const vm = require('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);
// 打印: { animal: 'cat', count: 12, name: 'kitty' }
使用 timeout
或 breakOnSigint
选项将导致新的事件循环和相应的线程被启动,其性能开销非零。
contextifiedObject
<Object> A contextified object as returned by thevm.createContext()
method.options
<Object>displayErrors
<boolean> Whentrue
, if anError
occurs while compiling thecode
, the line of code causing the error is attached to the stack trace. Default:true
.timeout
<integer> Specifies the number of milliseconds to executecode
before terminating execution. If execution is terminated, anError
will be thrown. This value must be a strictly positive integer.breakOnSigint
<boolean> Iftrue
, the execution will be terminated whenSIGINT
(Ctrl+C) is received. Existing handlers for the event that have been attached viaprocess.on('SIGINT')
will be disabled during script execution, but will continue to work after that. If execution is terminated, anError
will be thrown. Default:false
.
- Returns: <any> the result of the very last statement executed in the 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.
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('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' }
Using the timeout
or breakOnSigint
options will result in new event loops
and corresponding threads being started, which have a non-zero performance
overhead.