function runInNewContext
Jump to headingrunInNewContext(): any
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
.
import vm from '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' }
Parameters Jump to heading
Jump to headingcode: string
The JavaScript code to compile and run.
optional
Jump to headingcontextObject: Context
An object that will be contextified
. If undefined
, a new object will be created.
optional
Jump to headingoptions: RunningCodeInNewContextOptions | string
Return Type Jump to heading
any
the result of the very last statement executed in the script.