Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท node:sqlite and Runtime Services

Node.js vm.Script class

Reference for vm.Script in node:vm: compile code once, run it in the current context or in new ones, set timeouts, and reuse cached data to skip parsing.

A vm.Script holds compiled JavaScript that has not run yet. Creating it parses the source once, and you can then run it many times: in the main context with runInThisContext(), in a prepared context with runInContext(), or in a fresh one with runInNewContext(). Syntax errors appear when you create the script, before anything executes.

Use it when you evaluate the same snippet repeatedly with different variables, such as a formula applied to every row of data, because parsing happens only once. For one-off evaluation, vm.runInNewContext() is shorter.

NODE
import vm from 'node:vm';

const script = new vm.Script('x * 2', { filename: 'double.js' });
console.log(script.runInNewContext({ x: 21 })); // 42

Try it

Node.js Compile once, run with different inputs

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.

Node.js Syntax errors, timeouts and cached data

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

NODE
new vm.Script(code: string, options?: string | {
  filename?: string,
  lineOffset?: number,
  columnOffset?: number,
  cachedData?: Buffer | TypedArray | DataView,
  importModuleDynamically?: Function | symbol,
}): Script

script.runInThisContext(options?): any
script.runInContext(contextifiedObject: object, options?): any
script.runInNewContext(contextObject?: object, options?): any
script.createCachedData(): Buffer
script.cachedDataRejected: boolean | undefined
script.sourceMapURL: string | undefined
Name Description
code JavaScript source to compile as a script.
filename Name shown in stack traces.
lineOffset, columnOffset Shift reported positions, useful when the code is embedded in a larger file.
cachedData Compiler data from an earlier createCachedData(). Speeds up compiling the same source.
runInContext(ctx) Runs in a context created with vm.createContext().
runInNewContext(obj) Runs in a fresh context built from obj.
runInThisContext() Runs in the current global context.
Run options timeout, displayErrors, breakOnSigint, and for runInNewContext also contextName and friends.

Returns: the run methods return the value of the last expression. createCachedData() returns a Buffer. cachedDataRejected is true or false when cachedData was supplied, otherwise undefined.

Errors: the constructor throws a SyntaxError for invalid code. Run methods propagate errors thrown by the code, and throw ERR_SCRIPT_EXECUTION_TIMEOUT when timeout expires.

Usage notes

  • The same script can run in many contexts, and each run starts with the globals of that context. The script object itself keeps no state.
  • A script is not a module. There is no import or export at the top level; for modules use vm.SourceTextModule (experimental, behind a flag).
  • runInThisContext() is not isolated. The code can read and change real globals. It cannot see variables of your module scope.
  • Not a security sandbox. As with every vm function, code can usually escape through objects you share. Do not run untrusted input.
  • Cached data helps start-up time only for big sources. Checking cachedDataRejected is necessary: the cache can be refused after a V8 version change.
  • Create the script once. Building a new Script in a loop repeats the parsing cost that the class exists to avoid.
  • Use filename always: error messages and stack traces become much more useful.