function
vm.createContext
If the given contextObject is an object, the vm.createContext() method will prepare that object and return a reference to it so that it can be used in calls to runInContext or script.runInContext(). Inside such scripts, the global object will be wrapped by the contextObject, retaining all of its existing properties but also having the built-in objects and functions any standard global object has. Outside of scripts run by the vm module, global variables will remain unchanged.
import { createContext, runInContext } from 'node:vm';
global.globalVar = 3;
const context = { globalVar: 1 };
createContext(context);
runInContext('globalVar *= 2;', context);
console.log(context);
// Prints: { globalVar: 2 }
console.log(global.globalVar);
// Prints: 3If contextObject is omitted (or passed explicitly as undefined), a new, empty contextified object will be returned.
When the global object in the newly created context is contextified, it has some quirks compared to ordinary global objects. For example, it cannot be frozen. To create a context without the contextifying quirks, pass vm.constants.DONT_CONTEXTIFY as the contextObject argument. See the documentation of vm.constants.DONT_CONTEXTIFY for details.
The vm.createContext() method is primarily useful for creating a single context that can be used to run multiple scripts. For instance, if emulating a web browser, the method can be used to create a single context representing a window's global object, then run all <script> tags together within that context.
The provided name and origin of the context are made visible through the Inspector API.
Either vm.constants.DONT_CONTEXTIFY or an object that will be contextified. If undefined, an empty contextified object will be created for backwards compatibility.
contextified object.
Referenced types
interface Context
interface CreateContextOptions
- importModuleDynamically?: number | DynamicModuleLoader<Context>
Used to specify how the modules should be loaded during the evaluation of this script when
import()is called. This option is part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see Support of dynamicimport()in compilation APIs. - microtaskMode?: 'afterEvaluate'
If set to
afterEvaluate, microtasks will be run immediately after the script has run. - origin?: string
Corresponds to the newly created context for display purposes. The origin should be formatted like a
URL, but with only the scheme, host, and port (if necessary), like the value of theurl.originproperty of a URL object. Most notably, this string should omit the trailing slash, as that denotes a path.