deno.com

function createContext

#createContext(): Context

Deno compatibility

The importModuleDynamically parameter is not supported.

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.

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

global.globalVar = 3;

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

vm.runInContext('globalVar *= 2;', context);

console.log(context);
// Prints: { globalVar: 2 }

console.log(global.globalVar);
// Prints: 3

If 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.

Parameters #

#contextObject: Context | constants.DONT_CONTEXTIFY
optional

Either vm.constants.DONT_CONTEXTIFY or an object that will be contextified. If undefined, an empty contextified object will be created for backwards compatibility.

#options: CreateContextOptions
optional

Return Type #

contextified object.