Node.js implements a flavor of vm.createContext() and friends that creates a context without contextifying its global object when vm.constants.DONT_CONTEXTIFY is used. This is suitable when users want to freeze the context (impossible when the global is contextified i.e. has interceptors installed) or speed up the global access if they don't need the interceptor behavior.
Before
const vm = require('node:vm');// Creating a context with a contextified global objectconst context = vm.createContext();// Attempting to freeze the global objecttry {vm.runInContext('Object.freeze(globalThis);', context);} catch (e) {console.log(e); // TypeError: Cannot freeze}// Accessing global variablesconsole.log(vm.runInContext('globalThis.foo = 1; foo;', context)); // 1
After
const vm = require('node:vm');// Using vm.constants.DONT_CONTEXTIFY to create a context with an ordinary global objectconst context = vm.createContext(vm.constants.DONT_CONTEXTIFY);// Successfully freezing the global objectvm.runInContext('Object.freeze(globalThis);', context);// Attempting to modify a variable that doesn't existtry {vm.runInContext('bar = 1; bar;', context);} catch (e) {console.log(e); // Uncaught ReferenceError: bar is not defined}
Build custom codemods
Use AI-powered codemod studio and automate undifferentiated tasks for yourself, colleagues or the community