runInContext
fun runInContext(contextifiedObject: Context, options: RunningScriptOptions = definedExternally): Any?(source)
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' }
Content copied to clipboard
Using the timeout
or breakOnSigint
options will result in new event loops and corresponding threads being started, which have a non-zero performance overhead.
Since
v0.3.1
Return
the result of the very last statement executed in the script.
Parameters
contextifiedObject
A contextified
object as returned by the vm.createContext()
method.