Node.js Reference ยท node:sqlite and Runtime Services
Node.js vm.runInNewContext() method
Reference for vm.runInNewContext(): evaluate a string of JavaScript with its own global object, pass variables in, read results back, and know the security limits.
vm.runInNewContext(code, contextObject, options) compiles a string of JavaScript and runs it in a brand-new V8 context. That context has its own set of built-ins (its own Object, Array, Math) and its own global object, whose properties are copied from, and linked to, the contextObject you pass in. The code cannot see your module's variables, require, process or setTimeout unless you hand them over.
It returns the value of the last expression in the code. It is used for evaluating small expressions with a controlled set of variables, templates, and configuration formulas, but it is not a security sandbox.
import vm from 'node:vm'; const result = vm.runInNewContext('price * qty', { price: 4, qty: 3 }); console.log(result); // 12
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
vm.runInNewContext(code: string, contextObject?: object, options?: string | { filename?: string, lineOffset?: number, columnOffset?: number, timeout?: number, displayErrors?: boolean, breakOnSigint?: boolean, contextName?: string, contextOrigin?: string, contextCodeGeneration?: { strings?: boolean, wasm?: boolean }, microtaskMode?: 'afterEvaluate', }): any
| Name | Description |
|---|---|
code |
The JavaScript source to run, as a script (not a module). |
contextObject |
Object whose properties become globals in the new context. Created empty if omitted. It is turned into a context by vm.createContext(). |
options |
A filename string, or an options object. filename appears in stack traces; timeout is in milliseconds. |
timeout |
Maximum synchronous run time in milliseconds. Throws an error with code ERR_SCRIPT_EXECUTION_TIMEOUT. |
microtaskMode |
'afterEvaluate' runs promise callbacks right after evaluation so that timeout covers them too. |
contextCodeGeneration |
Allow or forbid eval()/new Function() (strings) and WebAssembly compilation (wasm) inside the context. |
Returns: the completion value of the code: the last evaluated expression.
Errors: exceptions thrown by the code propagate to the caller, as do syntax errors; a timeout throws ERR_SCRIPT_EXECUTION_TIMEOUT.
Usage notes
- It is not a security boundary. Code in a context can often climb back out, for instance through any object you pass in (
obj.constructor.constructor('return process')()). Never use it to run untrusted code. Use a separate process, container or a worker with restrictions instead. - The context object is mutated. Global assignments in the code add properties to it, which is how you read results back besides the return value.
- Each call creates a new context, which is relatively expensive. To run many snippets with the same globals, create a context once with
vm.createContext()and callvm.runInContext(), or compile withvm.Script. - Objects are not
instanceofacross contexts. Arrays, errors and objects from inside have different prototypes than yours. UseArray.isArray()and avoidinstanceofchecks. letandconstat top level do not become context properties, onlyvarand function declarations and implicit globals do.timeoutonly covers synchronous code. Callbacks from timers or promises started inside are not interrupted unless you setmicrotaskMode.- The context has no timers,
processorrequireunless you pass them in. It only has what the JavaScript language itself provides. - Stability:
node:vmis documented as stable, but the security note above applies to every version.
Related
vm.Script,require(),structuredClone()- Lessons: Worker threads, Web security