node:vm API Reference

Node.js vm module — script compilation and context-scoped evaluation (approximate isolation)

Node.js vm module, resolvable via both ESM import and CommonJS require. Implemented as a guest-JavaScript shim.

Isolation is approximate. Unlike Node, a “context” here is not a separate V8 realm. runInThisContext uses an indirect eval; runInNewContext / runInContext route free identifiers through a with-scoped sandbox built with new Function. Inside contextified code, this and globalThis both resolve to the sandbox (property definitions, reflection queries such as Reflect.ownKeys(this), and reads all land on the sandbox object), and the contextify marker is invisible to reflection. Intrinsics are still shared with the host realm, however — do not rely on node:vm as a security boundary; use the filesystem sandbox and process-level isolation instead.

Implemented surface

ExportDescription
Script(code[, options])Compile a script; instances expose runInThisContext, runInContext, runInNewContext, and createCachedData.
createContext([contextObject])Wrap an object as a sandbox usable with runInContext.
isContext(object)Whether an object has been contextified.
compileFunction(code[, params][, options])Compile a function body.
runInThisContext(code[, options])Evaluate in the current global scope (indirect eval).
runInContext(code, context[, options])Evaluate against a contextified sandbox.
runInNewContext(code[, context][, options])Evaluate against a fresh sandbox.
measureMemory([options])Returns a resolved memory-measurement result.
constantsThe vm constants object.

SourceTextModule is present with a minimal status lifecycle only — it does not link or evaluate ES module imports.

See also