Script.prototype.runInNewContext - Node documentation
method Script.prototype.runInNewContext

Usage in Deno

import { Script } from "node:vm";
Script.prototype.runInNewContext(
contextObject?: Context,
): any

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' }]

Parameters

optional
contextObject: Context

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

Return Type

any

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