vm.createContext([contextObject[, options]])


  • contextObject <Object> | <undefined> vm.constants.DONT_CONTEXTIFY 或将成为 contextified 的对象。如果是 undefined,将创建一个空的上下文化对象以实现向后兼容。

    ¥contextObject <Object> | <undefined> Either vm.constants.DONT_CONTEXTIFY or an object that will be contextified. If undefined, an empty contextified object will be created for backwards compatibility.

  • options <Object>

    • name <string> 新创建的上下文的可读名称。默认值:'VM Context i',其中 i 是所创建上下文的升序数字索引。

      ¥name <string> Human-readable name of the newly created context. Default: 'VM Context i', where i is an ascending numerical index of the created context.

    • origin <string> 起源 对应于新创建的上下文,用于显示目的。来源的格式应该像 URL,但只有协议、主机和端口(如果需要),就像 URL 对象的 url.origin 属性的值。最值得注意的是,该字符串应省略尾部斜杠,因为它表示路径。默认值:''

      ¥origin <string> Origin corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the url.origin property of a URL object. Most notably, this string should omit the trailing slash, as that denotes a path. Default: ''.

    • codeGeneration <Object>

      • strings <boolean> 如果设置为 false,则任何对 eval 或函数构造函数(FunctionGeneratorFunction 等)的调用都将抛出 EvalError。默认值:true

        ¥strings <boolean> If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) will throw an EvalError. Default: true.

      • wasm <boolean> 如果设置为 false,则任何编译 WebAssembly 模块的尝试都将抛出 WebAssembly.CompileError。默认值:true

        ¥wasm <boolean> If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. Default: true.

    • microtaskMode <string> 如果设置为 afterEvaluate,微任务(通过 Promiseasync function 安排的任务)将在脚本运行通过 script.runInContext() 后立即运行。在这种情况下,它们包含在 timeoutbreakOnSigint 范围内。

      ¥microtaskMode <string> If set to afterEvaluate, microtasks (tasks scheduled through Promises and async functions) will be run immediately after a script has run through script.runInContext(). They are included in the timeout and breakOnSigint scopes in that case.

    • importModuleDynamically <Function> | <vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER> 用于指定在没有引用脚本或模块的情况下在此上下文中调用 import() 时应如何加载模块。此选项是实验模块 API 的一部分。不建议在生产环境中使用它。详细信息参见 编译 API 中支持动态 import()

      ¥importModuleDynamically <Function> | <vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER> Used to specify the how the modules should be loaded when import() is called in this context without a referrer script or module. This option is part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see Support of dynamic import() in compilation APIs.

  • 返回:<Object> 上下文对象。

    ¥Returns: <Object> contextified 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),将返回一个新的空 contextified 对象。

¥If contextObject is omitted (or passed explicitly as undefined), a new, empty contextified object will be returned.

当新创建的上下文中的全局对象是 contextified 时,与普通全局对象相比,它有一些怪癖。例如,它不能被冻结。要创建没有上下文怪癖的上下文,请将 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.

提供的上下文的 nameorigin 通过检查器 API 可见。

¥The provided name and origin of the context are made visible through the Inspector API.