Node.js vm Module

Java FileNode.js Built-in Modules


Node.js'svmThe module is a virtual machine module for JavaScript, which allows you to compile and run code in a V8 virtual machine context. This module provides a way to execute JavaScript code in an isolated context, isolated from the current process but capable of using a specific context.

Main Features

  • Isolated execution environment: Can create a sandbox environment isolated from the main program
  • Controllable context: Allows customization of global objects and context
  • Secure execution: Reduces the impact of untrusted code on the main program
  • Performance optimization: Can pre-compile scripts to improve efficiency of repeated execution

Core API Introduction

vm.Script Class

vm.ScriptThis class is used to compile code without running it. The compiled script can be executed multiple times.

Example

const vm = require('vm');

const script = new vm.Script('x + y', {
  filename: 'add.vm',
  lineOffset: 0,
  displayErrors: true
});

Parameter Description

  • code: The JavaScript code string to be compiled
  • options(Optional):
    • filename: Filename used for stack traces
    • lineOffset: Line number offset of the first line of the script
    • columnOffset: Column offset of the first column of the script
    • displayErrors: Whether to output errors to stderr when errors occur
    • timeout: Execution timeout (milliseconds)
    • cachedData: Contains optional V8 code cache data

vm.createContext([contextObject])

Creates a new context object, optionally using an existing object for initialization.

Example

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

script.runInContext(contextifiedObject[, options])

Runs the compiled script in the specified context.

Example

const result = script.runInContext(context);
console.log(result); // Outputs 30

Use Cases

1. Safely Execute Untrusted Code

Example

const vm = require('vm');

const untrustedCode = `
  process.exit(1); // Malicious code
`;

try {
  const script = new vm.Script(untrustedCode);
  const context = vm.createContext({});
  script.runInContext(context);
} catch (err) {
  console.log('Security interception:', err.message);
}

2. Create an Isolated Test Environment

Example

const vm = require('vm');

const testCode = `
  function add(a, b) {
    return a + b;
  }
  add(2, 3);
`;

const context = vm.createContext({});
const result = vm.runInContext(testCode, context);
console.log('Test result:', result); // Outputs 5

3. Template Engine Implementation

Example

const vm = require('vm');

function render(template, data) {
  const code = `\`${template}\``;
  const context = vm.createContext(data);
  return vm.runInContext(code, context);
}

const template = 'Hello, ${name}! You are ${age} years old.';
const result = render(template, { name: 'Alice', age: 25 });
console.log(result); // Outputs "Hello, Alice! You are 25 years old."

Security Considerations

Althoughvmthe module provides a certain degree of isolation, it is not a completely secure sandbox:

  1. Memory limit: Malicious code can still cause memory exhaustion
  2. Synchronous operations: Infinite loops will block the event loop
  3. Context escape: In some cases, global objects can be accessed

For scenarios requiring higher security, consider:

  • Use OS-level isolation such as Docker containers
  • Use specialized sandbox solutions such as thesandboxmodule
  • Limit execution time and resource usage

Performance Optimization Tips

1. Reuse Compiled Scripts

Example

const vm = require('vm');
const script = new vm.Script('x * y');

// Execute the same compiled script multiple times
for (let i = 0; i < 100; i++) {
  const context = vm.createContext({ x: i, y: 2 });
  console.log(script.runInContext(context));
}

2. Use cachedData to Speed Up Compilation

Example

const vm = require('vm');

// Compile for the first time and get cache data
const script1 = new vm.Script('x + y');
const cachedData = script1.createCachedData();

// Later use cache data to speed up compilation
const script2 = new vm.Script('x + y', { cachedData });

3. Set a Reasonable timeout

Example

const script = new vm.Script('while(true) {}', { timeout: 100 });
try {
  script.runInContext(vm.createContext({}));
} catch (err) {
  console.log('Execution timeout:', err.message);
}

Differences from eval

Feature vm module eval
Execution environment Can create isolated context Uses current scope
Security Relatively high Relatively low
Performance Can be pre-compiled, high efficiency for repeated execution Requires parsing every time
Debugging support Supports filename and line number mapping Not supported
Resource control Can set limits such as timeout No control

Summary

Node.js'svmThe module is a powerful tool, especially suitable for scenarios that require isolated execution of JavaScript code. Although it is not a completely secure sandbox solution, in many cases it provides sufficient security isolation and performance optimization capabilities. When used correctly, it can greatly improve the security and flexibility of applications.

Java FileNode.js Built-in Modules

Other Extensions