VM context, or Virtual Machine context

In Node.js, a VM context, or Virtual Machine context, refers to an isolated global object environment where JavaScript code can be executed using the node:vm module. This module provides APIs for compiling and running code within V8 Virtual Machine contexts, offering a sandboxed environment for code execution. Key aspects of Node.js VM contexts include:

Isolation: Each VM context provides a distinct global object, separate from the main Node.js environment and other VM contexts. This means that variables and functions defined within one context do not directly affect or leak into other contexts or the main application scope.

vm.createContext(): This method is used to create or prepare a “contextified” sandbox object. If a plain JavaScript object is provided, createContext() will prepare it to serve as the global object for the new VM context, adding built-in objects and functions typically found in a global environment.

vm.runInContext(): This method compiles and executes a given JavaScript code string within a specified contextified sandbox. The code running within this context will use the contextified sandbox object as its global object.

Use Cases:

VM contexts are commonly used for:

Important Note: While VM contexts offer a degree of isolation, they are not a foolproof security mechanism for running highly untrusted code. For robust security, running untrusted code in a separate process with appropriate security measures is generally recommended.

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

const x = 1;

const context = { x: 2 };
vm.createContext(context); // Contextify the object.

const code = 'x += 40; var y = 17;';
// `x` and `y` are global variables in the context.
// Initially, x has the value 2 because that is the value of context.x.
vm.runInContext(code, context);

console.log(context.x); // 42
console.log(context.y); // 17

console.log(x); // 1; y is not defined.

nodejs.org/api/vm w3schools