method Script.prototype.runInNewContext
Jump to headingScript.prototype.runInNewContext(contextObject?: Context,options?: RunningScriptInNewContextOptions,): anyFirst contextifies the given contextObject, runs the compiled code contained
by the vm.Script object within the created context, and returns the result.
Running code does not have access to local scope.
The following example compiles code that sets a global variable, then executes
the code multiple times in different contexts. The globals are set on and
contained within each individual context.
import vm from 'node:vm';
const script = new vm.Script('globalVar = "set"');
const contexts = [{}, {}, {}];
contexts.forEach((context) => {
script.runInNewContext(context);
});
console.log(contexts);
// Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]
Parameters Jump to heading
optional
Jump to headingcontextObject: ContextAn object that will be contextified. If undefined, a new object will be created.
optional
Jump to headingoptions: RunningScriptInNewContextOptionsReturn Type Jump to heading
anythe result of the very last statement executed in the script.