runInContext - Node documentation
function runInContext

Usage in Deno

import { runInContext } from "node:vm";
runInContext(
code: string,
contextifiedObject: Context,
options?: RunningCodeOptions | string,
): any

The vm.runInContext() method compiles code, runs it within the context of the contextifiedObject, then returns the result. Running code does not have access to the local scope. The contextifiedObject object must have been previously contextified using the createContext method.

If options is a string, then it specifies the filename.

The following example compiles and executes different scripts using a single contextified object:

const vm = require('node:vm');

const contextObject = { globalVar: 1 };
vm.createContext(contextObject);

for (let i = 0; i < 10; ++i) {
  vm.runInContext('globalVar *= 2;', contextObject);
}
console.log(contextObject);
// Prints: { globalVar: 1024 }

Parameters

code: string

The JavaScript code to compile and run.

contextifiedObject: Context

The contextified object that will be used as the global when the code is compiled and run.

optional
options: RunningCodeOptions | string

Return Type

any

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