vm.constants.DONT_CONTEXTIFY
当在 vm API 中将此常量作为 contextObject 参数使用时,会指示 Node.js 创建一个上下文,而不会以 Node.js 特有的方式将其全局对象封装在另一个对象中。因此,新上下文中的 globalThis 值的行为将更接近普通对象。
【This constant, when used as the contextObject argument in vm APIs, instructs Node.js to create
a context without wrapping its global object with another object in a Node.js-specific manner.
As a result, the globalThis value inside the new context would behave more closely to an ordinary
one.】
const vm = require('node:vm');
// Use vm.constants.DONT_CONTEXTIFY to freeze the global object.
const context = vm.createContext(vm.constants.DONT_CONTEXTIFY);
vm.runInContext('Object.freeze(globalThis);', context);
try {
vm.runInContext('bar = 1; bar;', context);
} catch (e) {
console.log(e); // Uncaught ReferenceError: bar is not defined
} 当 vm.constants.DONT_CONTEXTIFY 作为 contextObject 参数传递给 vm.createContext() 时,返回的对象是新创建上下文中全局对象的类似代理的对象,具有更少的 Node.js 特有问题。它与新上下文中的 globalThis 值相同,可以从上下文外部修改,并且可以直接用于访问新上下文中的内置对象。
【When vm.constants.DONT_CONTEXTIFY is used as the contextObject argument to vm.createContext(),
the returned object is a proxy-like object to the global object in the newly created context with
fewer Node.js-specific quirks. It is reference equal to the globalThis value in the new context,
can be modified from outside the context, and can be used to access built-ins in the new context directly.】
const vm = require('node:vm');
const context = vm.createContext(vm.constants.DONT_CONTEXTIFY);
// Returned object is reference equal to globalThis in the new context.
console.log(vm.runInContext('globalThis', context) === context); // true
// Can be used to access globals in the new context directly.
console.log(context.Array); // [Function: Array]
vm.runInContext('foo = 1;', context);
console.log(context.foo); // 1
context.bar = 1;
console.log(vm.runInContext('bar;', context)); // 1
// Can be frozen and it affects the inner context.
Object.freeze(context);
try {
vm.runInContext('baz = 1; baz;', context);
} catch (e) {
console.log(e); // Uncaught ReferenceError: baz is not defined
}