script.runInContext(contextifiedObject[, options])
在给定的 contextifiedObject
中运行 vm.Script
对象包含的编译代码并返回结果。
运行代码无权访问本地作用域。
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
, receivingSIGINT
(Ctrl+C) will terminate execution and throw anError
. Existing handlers for the event that have been attached viaprocess.on('SIGINT')
are disabled during script execution, but continue to work after that. 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('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' }
Using the timeout
or breakOnSigint
options will result in new event loops
and corresponding threads being started, which have a non-zero performance
overhead.