Skip to content

node:vm

How Elide supports Node's vm module: Script, createContext, compileFunction and runIn*Context, and where contexts, code-generation options and modules differ.

On this page

node:vm provides Script, createContext, compileFunction, runInContext, runInNewContext and runInThisContext from Node’s vm, including the timeout option.

Example

js
// vm.mjs
import vm from "node:vm";

const context = vm.createContext({ price: 20, qty: 3 });
console.log(vm.runInContext("price * qty", context));

const script = new vm.Script("count = (typeof count === 'number' ? count : 0) + 1");
script.runInContext(context);
script.runInContext(context);
console.log(context.count);

try {
  vm.runInNewContext("while (true) {}", {}, { timeout: 50 });
} catch (error) {
  console.log(error.code);
}
utf-8 · js · Lines: 16

elide run vm.mjs prints:

text
60
2
ERR_SCRIPT_EXECUTION_TIMEOUT
utf-8 · text · Lines: 3

Differences from Node

  • A context shares intrinsics (Symbol, Proxy, Object) with the host realm; it is not a security boundary.
  • codeGeneration: { strings: false } is not enforced; eval still runs in the context.
  • vm.constants.DONT_CONTEXTIFY is rejected by createContext.
  • SyntaxError messages use different wording, such as Expected eof but found }.
  • SourceTextModule emits an ExperimentalWarning and does not support full linking and evaluation.

Reference

Status: Full · 80 of 95 suite tests pass (84.2%) · since 1.1.0

Exports

ExportKindStatusNotes
ScriptclassFullrunInThisContext(), runInNewContext()
createContext()functionFullCreates a new execution context (sandbox)
runInNewContext()functionFullCompiles code, creates a new context, and runs the code in that context
runInThisContext()functionFullCompiles and runs code within the current global context
isContext()functionFullReturns whether the given object is a contextified sandbox

Tests: node-api node:vm: 80 pass, 15 fail, 0 error, 3 skipped. Failing: test-vm-basic.js, test-vm-codegen.js, test-vm-context-dont-contextify.js, test-vm-function-declaration.js, test-vm-global-property-prototype.js, test-vm-global-setter.js, test-vm-harmony-symbols.js, test-vm-module-after-evaluate.js, and 7 more.

Was this page helpful?