Skip to main content
Script.prototype.runInContext - vm - Node documentation
method Script.prototype.runInContext

Usage in Deno

import { Script } from "node:vm";
Script.prototype.runInContext(
contextifiedObject: Context,
): any

Runs the compiled code contained by the vm.Script object within the given contextifiedObject and returns the result. Running code does not have access to local scope.

The following example compiles code that increments a global variable, sets the value of another global variable, then execute the code multiple times. The globals are contained in the context object.

import vm from 'node:vm';

const context = {
  animal: 'cat',
  count: 2,
};

const script = new vm.Script('count += 1; name = "kitty";');

vm.createContext(context);
for (let i = 0; i < 10; ++i) {
  script.runInContext(context);
}

console.log(context);
// Prints: { animal: 'cat', count: 12, name: 'kitty' }

Using the timeout or breakOnSigint options will result in new event loops and corresponding threads being started, which have a non-zero performance overhead.

Parameters

contextifiedObject: Context

A contextified object as returned by the vm.createContext() method.

optional
options: RunningScriptOptions

Return Type

any

the result of the very last statement executed in the script.

Back to top