VM

vm.runInNewContext()

Executes reviewed code with a new context. Context globals differ from the calling scope. It must not be used to execute hostile source. Tested on Node.js 22.16.0. Example output (one line per entry): ["6 8"].

Formal Syntax & Structure

nodejs syntaxnodejs
vm.runInNewContext(code[, contextObject[, options]])

Parameters & Attributes

NameTypeDescription
codestringReviewed source.
contextObjectobjectInitial globals.
optionsobjectExecution options.

Return Value

unknown

Completion value.

Working Example

Example Snippetnodejs
import { runInNewContext } from 'node:vm';const stock = 8;console.log(runInNewContext('stock * 2', { stock: 3 }, { timeout: 100 }), stock);
Node.js Reference