Skip to main content

runInContext

method Script.prototype.runInContext
Jump to headingScript.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 Jump to heading

Jump to headingcontextifiedObject: Context

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

Return Type Jump to heading

any

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

Back to top