vm.createContext([contextObject[, options]])
contextObject<Object> | <undefined> 可以是vm.constants.DONT_CONTEXTIFY或者将被 情境化 的对象。如果为undefined,将会创建一个空的 contextified 对象以保证向后兼容性。options<Object>name<string> 新创建上下文的人类可读名称。 默认值:'VM Context i',其中i是已创建上下文的递增数字索引。origin<string> 起源 对应于新创建的用于显示的上下文。origin 应该像 URL 一样格式化,但只包含方案、主机和端口(如有必要),类似于URL对象的url.origin属性的值。最重要的是,该字符串应省略末尾的斜杠,因为斜杠表示路径。默认值:''。codeGeneration<Object>microtaskMode<string> 如果设置为afterEvaluate,微任务(通过Promise和async function调度的任务)将在脚本执行完script.runInContext()后立即运行。在这种情况下,它们包含在timeout和breakOnSigint的作用域中。importModuleDynamically<Function> | <vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER> 用于指定在此上下文中调用import()时模块应如何加载,当没有引用脚本或模块时。该选项是实验性模块 API 的一部分。我们不建议在生产环境中使用它。有关详细信息,请参见 在编译 API 中支持动态import()。
- 返回:<Object> 已上下文化的对象。
如果给定的 contextObject 是一个对象,vm.createContext() 方法将 准备那个对象 并返回它的引用,以便可以在调用 vm.runInContext() 或 script.runInContext() 时使用。在这些脚本内部,全局对象将被 contextObject 封装,保留其所有现有属性,同时还拥有任何标准 全局对象 的内置对象和函数。在由 vm 模块运行的脚本之外,全局变量将保持不变。
【If the given contextObject is an object, the vm.createContext() method will prepare that
object and return a reference to it so that it can be used in
calls to vm.runInContext() or script.runInContext(). Inside such
scripts, the global object will be wrapped by the contextObject, retaining all of its
existing properties but also having the built-in objects and functions any
standard global object has. Outside of scripts run by the vm module, global
variables will remain unchanged.】
const vm = require('node:vm');
global.globalVar = 3;
const context = { globalVar: 1 };
vm.createContext(context);
vm.runInContext('globalVar *= 2;', context);
console.log(context);
// Prints: { globalVar: 2 }
console.log(global.globalVar);
// Prints: 3 如果省略 contextObject(或显式传入 undefined),将返回一个新的、空的 情境化 对象。
【If contextObject is omitted (or passed explicitly as undefined), a new,
empty contextified object will be returned.】
当新创建的上下文中的全局对象是 情境化 时,与普通全局对象相比,它有一些特殊情况。例如,它无法被冻结。要创建没有这些上下文特殊情况的上下文,请将 vm.constants.DONT_CONTEXTIFY 作为 contextObject 参数传入。详情请参阅 vm.constants.DONT_CONTEXTIFY 的文档。
【When the global object in the newly created context is contextified, it has some quirks
compared to ordinary global objects. For example, it cannot be frozen. To create a context
without the contextifying quirks, pass vm.constants.DONT_CONTEXTIFY as the contextObject
argument. See the documentation of vm.constants.DONT_CONTEXTIFY for details.】
vm.createContext() 方法主要用于创建一个可以用于运行多个脚本的单一上下文。例如,在模拟网页浏览器时,该方法可以用于创建一个表示窗口全局对象的单一上下文,然后在该上下文中一起运行所有 <script> 标签。
【The vm.createContext() method is primarily useful for creating a single
context that can be used to run multiple scripts. For instance, if emulating a
web browser, the method can be used to create a single context representing a
window's global object, then run all <script> tags together within that
context.】
通过检查器 API,可以看到所提供的上下文的 name 和 origin。
【The provided name and origin of the context are made visible through the
Inspector API.】