node:vm provides Node-shaped script compilation and context APIs.
A context is not a security boundary. Intrinsics are shared with the host realm. Use process and filesystem isolation for untrusted code.
| Export | Purpose |
|---|---|
Script | Compile code and run it in this context or a sandbox context. |
createContext() / isContext() | Contextify an object and check its marker. |
compileFunction() | Compile a function body. |
runInThisContext() | Evaluate in the current global scope. |
runInContext() | Evaluate against a contextified object. |
runInNewContext() | Evaluate against a new sandbox object. |
measureMemory() | Return a Promise for a memory result. |
constants | VM constants. |
const vm = require("node:vm");
const sandbox = { x: 2 };
vm.createContext(sandbox);
vm.runInContext("x + 3", sandbox); // 5SourceTextModule exposes only a limited lifecycle and does not provide full
module linking and evaluation.