Skip to main content

runInContext

function runInContext
Jump to headingrunInContext(
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:

import vm from '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 Jump to heading

Jump to headingcode: string

The JavaScript code to compile and run.

Jump to headingcontextifiedObject: Context

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

optional
Jump to headingoptions: RunningCodeOptions | string

Return Type Jump to heading

any

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

Back to top