runInNewContext

fun runInNewContext(contextObject: Context = definedExternally, options: RunningScriptInNewContextOptions = definedExternally): Any?(source)

First 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.

const vm = require('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' }]

Since

v0.3.1

Return

the result of the very last statement executed in the script.

Parameters

contextObject

An object that will be contextified. If undefined, a new object will be created.