This method is a shortcut to (new vm.Script(code, options)).runInContext(vm.createContext(options), options)
. If options
is a string, then it specifies the filename.
It does several things at once:
- Creates a new context.
- If
contextObject
is an object, contextifies it with the new context. IfcontextObject
is undefined, creates a new object and contextifies it. IfcontextObject
isvm.constants.DONT_CONTEXTIFY
, don't contextify anything. - Compiles the code as a
vm.Script
- Runs the compield code within the created context. The code does not have access to the scope in which this method is called.
- Returns the result.
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' }
// This would throw if the context is created from a contextified object.
// vm.constants.DONT_CONTEXTIFY allows creating contexts with ordinary global objects that
// can be frozen.
const frozenContext = vm.runInNewContext('Object.freeze(globalThis); globalThis;', vm.constants.DONT_CONTEXTIFY);