Node.js Virtual Machine (VM) Module

Atakan Erturk
Insider Engineering
5 min readJul 15, 2024

As a JavaScript runtime environment, Node.js offers developers a variety of powerful tools. One of these tools, the VM (Virtual Machine) module, allows you to run JavaScript code in an isolated environment. In this article, we will explain what the Node.js VM module is, its advantages, how to use it, and all that with sample codes.

What is a Virtual Machine?

A virtual machine (VM) is a layer of software that runs on a physical computer and provides a virtual environment. This virtual environment allows operating systems and applications to run in isolation. VMs offer advantages such as hardware independence, security, and resource management.

What is Node.js VM Module?

The VM module allows you to run JavaScript code within a virtual machine isolated from the main context of your Node.js application. This is a significant advantage in terms of security and code isolation. The VM module is a built-in Node.js module called vm, and it provides several methods for evaluating, compiling, and executing JavaScript code.

What are the advantages?

  1. Code Isolation: The VM module allows JavaScript code to be isolated from the main application. This is especially important for security when running code from external sources or user-supplied code.
  2. Security: By running code in an isolated environment, you can minimize potential vulnerabilities that could compromise the security of the host application.
  3. Performance: The VM module ensures fast compilation and execution of code. This can contribute to performance improvements.
  4. Flexibility: You can increase the flexibility of your application by running different code snippets in isolated environments.
  5. Testability: The VM module allows different code snippets to be tested independently. This provides a more modular and testable code base.

What are the disadvantages?

  1. Limited Capabilities: The VM module provides a limited runtime environment where certain JavaScript features and Node.js APIs are not available.
  2. Resource Management: When working with the VM module, managing resources such as memory and CPU usage is important. Mismanagement can lead to performance problems.
  3. Security Risks: Although it provides isolation, it does not guarantee that user-supplied code is completely secure. Additional security measures should be taken.

Using the VM Module

To start using the VM module, you must first import the VM module:

const vm = require('vm');

Sample Usage Scenarios

  1. Running Simple Code: You can use the vm.runInThisContext or vm.runInNewContext functions to run a simple JavaScript code in the VM.
const vm = require('vm');
const code = 'const a = 5; const b = 10; a + b;';
const result = vm.runInThisContext(code);
console.log(result); // 15

2. Creating a New Context: You can create a new isolated context with the vm.createContext and vm.runInContext functions.

const vm = require('vm');

const context = { x: 10 };
vm.createContext(context);

const code = 'x += 20; var y = 30;';
vm.runInContext(code, context);

console.log(context.x); // 30
console.log(context.y); // 30

3. Script Object Usage: The vm.Script object allows you to run compiled JavaScript code repeatedly. This provides performance improvements and increases code reusability.

const vm = require('vm');

const code = 'a + b';
const script = new vm.Script(code);

const context1 = { a: 1, b: 2 };
const context2 = { a: 10, b: 20 };

vm.createContext(context1);
vm.createContext(context2);

console.log(script.runInContext(context1)); // 3
console.log(script.runInContext(context2)); // 30

Advanced Usage with VM Module

The VM module can also be used for more complex applications, going beyond simple usage scenarios. For example, it is ideal for safely executing dynamic code from the user or creating a sandbox environment.

  1. Creating a Sandbox: You can use a sandbox to run user-supplied code in an isolated environment.
const vm = require('vm');

const sandbox = {
animal: 'cat',
count: 2
};

vm.createContext(sandbox); // Contextified object.

const script = new vm.Script('count += 1; name = "kitty";');
script.runInContext(sandbox);

console.log(sandbox.count); // 3
console.log(sandbox.name); // 'kitty'

2. Secure Code Execution: You can use the VM module to safely run potentially malicious code from the user.

const vm = require('vm');

const userInput = 'globalVar = 10'; // User input that tries to modify global variable
const context = {};

vm.createContext(context);

try {
vm.runInContext(userInput, context, { timeout: 1000 });
} catch (e) {
console.error('Error running user input:', e);
}

console.log(globalVar); // undefined, global variable not modified
console.log(context.globalVar); // 10, only modified within the context

3. Dynamic Code Analysis: The VM module can be used to analyze dynamically generated or user-provided codes. For example, it can be used as a code review tool.

const vm = require('vm');
const code = `
const isSafe = (input) => input.includes('safe');
isSafe('this is safe');
`;
const script = new vm.Script(code);
const result = script.runInThisContext();
console.log(result); // true

Real Life Usage Scenarios

  1. Code Execution in Web Applications: VM module can be used to securely execute user-provided code in web applications. For example, on a code sharing platform you can run user codes in an isolated environment.
  2. Test Environments: In software testing, the VM module can be used to run different pieces of code in isolated test environments. This ensures that the tests are safe and reproducible.
  3. Dynamic Content Generation: The VM module can be used to securely evaluate and execute dynamically generated JavaScript codes. For example, it can be used to process user-supplied templates.

Conclusion

The Node.js VM module is a powerful tool for running JavaScript code in an isolated and secure environment. With its advantages such as code isolation, security and performance, it is ideal for running user-provided codes or evaluating dynamically generated codes. By using the VM module, you can make your applications more secure, flexible and testable.

In this article, we explained in detail what the Node.js VM module is, its advantages, how to use it, and with various examples. By using the VM module in your projects, you can develop safe and high-performance applications.

For more information, you can refer to Node.js Official Documentation

--

--