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;evalstill runs in the context.vm.constants.DONT_CONTEXTIFYis rejected bycreateContext.SyntaxErrormessages use different wording, such asExpected eof but found }.SourceTextModuleemits anExperimentalWarningand does not support full linking and evaluation.
Reference
Status: Full · 80 of 95 suite tests pass (84.2%) · since 1.1.0
Exports
| Export | Kind | Status | Notes |
|---|---|---|---|
Script | class | Full | runInThisContext(), runInNewContext() |
createContext() | function | Full | Creates a new execution context (sandbox) |
runInNewContext() | function | Full | Compiles code, creates a new context, and runs the code in that context |
runInThisContext() | function | Full | Compiles and runs code within the current global context |
isContext() | function | Full | Returns 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.