Loading lesson path
Concept visual
Start at both ends
The VM (Virtual Machine) module allows you to compile and run code within isolated contexts.
While the VM module provides isolation from the main JavaScript environment, it is not a completely secure sandbox. It should not be used as the sole security mechanism for running untrusted code.
To use the VM module, you need to import it in your Node.js application:
const vm = require('vm');The VM module has several key components:
A compiled JavaScript code that can be executed multiple times in different contexts
An isolated global object where scripts execute, similar to a sandboxed environment
An object that has been associated with a VM context and serves as its global object
The simplest way to use the VM module is to run code in a context:
const vm = require('vm');
// Create a context object const context = { x: 2 };
// Compile and run a script in the context vm.createContext(context);
vm.runInContext('x = x * 2; y = 10;', context);
// Inspect the modified context console.log(context); // Outputs: { x: 4, y: 10 }We create a context object with a variable x We "contextify" this object using vm.createContext() We run JavaScript code in this context that modifies x and creates y The changes are reflected in the context object
Description vm.Script(code[, options]) Creates a new Script object that represents compiled code script.runInContext(contextObject[, options]) Runs the compiled code in the specified context script.runInNewContext([contextObject][, options]) Runs the compiled code in a new context script.runInThisContext([options]) Runs the compiled code in the current context
Description vm.createContext([contextObject][, options]) Creates a new context which can be used for script execution vm.isContext(object) Checks if an object has been contextified vm.runInContext(code, contextObject[, options]) Compiles and executes code in the given context vm.runInNewContext(code[, contextObject][, options]) Compiles and executes code in a new context vm.runInThisContext(code[, options]) Compiles and executes code in the current context
Formula
For better performance when executing the same code multiple times, you can pre - compile it using theconst vm = require('vm');
// Compile the script once const script = new vm.Script('x += 40; let z = 30;');
// Create multiple contexts const context1 = { x: 10 };
const context2 = { x: 20 };
// Contextify the objects vm.createContext(context1);
vm.createContext(context2);
// Run the same script in different contexts script.runInContext(context1);
script.runInContext(context2);
console.log(context1); // Outputs: { x: 50, z: 30 }
console.log(context2); // Outputs: { x: 60, z: 30 }