VM

vm.runInContext()

Runs reviewed JavaScript in an existing context. Mutations can persist across calls. A synchronous timeout is not a general resource or security boundary. Tested on Node.js 22.16.0. Example output (one line per entry): ["3"].

Formal Syntax & Structure

nodejs syntaxnodejs
vm.runInContext(code, contextifiedObject[, options])

Parameters & Attributes

NameTypeDescription
codestringReviewed source.
contextifiedObjectobjectExisting context.
optionsobjectExecution options.

Return Value

unknown

Completion value.

Working Example

Example Snippetnodejs
import { createContext, runInContext } from 'node:vm';const c = createContext({ stock: 5 });runInContext('stock -= 2', c, { timeout: 100 });console.log(runInContext('stock', c, { timeout: 100 }));
Node.js Reference