runInNewContext

external fun runInNewContext(code: String, contextObject: Context = definedExternally, options: RunningCodeInNewContextOptions = definedExternally): Any?(source)
external fun runInNewContext(code: String, contextObject: Context = definedExternally, options: String = definedExternally): Any?(source)

The vm.runInNewContext() first contextifies the given contextObject (or creates a new contextObject if passed as undefined), compiles the code, runs it within the created context, then returns the result. Running code does not have access to the local scope.

If options is a string, then it specifies the filename.

The following example compiles and executes code that increments a global variable and sets a new one. These globals are contained in the contextObject.

const vm = require('node:vm');

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

vm.runInNewContext('count += 1; name = "kitty"', contextObject);
console.log(contextObject);
// Prints: { animal: 'cat', count: 3, name: 'kitty' }

Since

v0.3.1

Return

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

Parameters

code

The JavaScript code to compile and run.

contextObject

An object that will be contextified. If undefined, a new object will be created.