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 }