The vm.createContext() method creates a separate execution context for running one or more scripts. If no contextObject is provided, it returns a new empty contextified object.
- If an object is provided, it becomes the global object inside scripts executed with
vm.runInContext()orscript.runInContext(). - Changes inside the context do not affect actual global variables outside the VM context.
Syntax
vm.createContext( contextObject, options )Parameters
- contextObject: It is the object which is contextified.
- options: It is optional and returns Object.
Return Value: It returns contextified JS object.
Use cases of vm.createContext()
- Running untrusted JavaScript code safely in an isolated environment.
- Creating separate execution environments with their own variables and global objects.
- Testing or sandboxing scripts without affecting the main Node.js application state.
Example 1: Creating an isolated execution context using vm.createContext() where changes to globalVar affect only the context object, not the actual global variable.
// Node.js program to demonstrate the
// vm.createContext([contextObject[, options]])
// method
// Including util and vm module
const util = require('util');
const vm = require('vm');
// Assigning value to the global variable
global.globalVar = 10;
// Defining Context object
const object = { globalVar: 4 };
// Contextifying stated object
// using createContext method
vm.createContext(object);
// Compiling code
vm.runInContext('globalVar /= 2;', object);
// Displays the context
console.log("Context: ", object);
// Displays value of global variable
console.log("Global Variable is ", global.globalVar);
Output:
Context: { globalVar: 2 }
Global Variable is 10
Here, globalVar in the context is 2 in output as (4/2 = 2) but the value of globalVar is still 10.
Example 2: Modifying variables inside a separate VM context using vm.createContext(), without changing the actual global variable.
// Node.js program to demonstrate the
// vm.createContext([contextObject[, options]])
// method
// Including util and vm module
const util = require('util');
const vm = require('vm');
// Assigning value to the global variable
global.globalVar = 5;
// Defining Context object
const object = { globalVar: 20 };
// Contextifying stated object
// using createContext method
vm.createContext(object);
// Compiling code
vm.runInContext('globalVar += 2;', object);
// Displays the context
console.log("Context: ", object);
// Displays value of global variable
console.log("Global Variable is ", global.globalVar);
Output:
Context: { globalVar: 22 }
Global Variable is 5
Here, globalVar in the context is 22 in output as (20+2 = 22) but the value of globalVar is still 5.
Reference: https://nodejs.org/api/vm.html#vm_vm_createcontext_contextobject_options