function runInContext
Jump to headingrunInContext(): anyThe 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: stringThe JavaScript code to compile and run.
Jump to headingcontextifiedObject: ContextThe contextified object that will be used as the global when the code is compiled and run.
optional
Jump to headingoptions: RunningCodeOptions | stringReturn Type Jump to heading
anythe result of the very last statement executed in the script.