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 用作 vm.createContext()contextObject 参数时,返回的对象是新创建的上下文中的全局对象的代理类对象,具有较少的 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
}