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


  • contextObject <Object>
  • options <Object>
    • name <string> 新创建上下文的人类可读名称。 默认值: 'VM Context i',其中 i 是已创建上下文的递增数字索引。
    • origin <string> 起源 对应于新创建的用于显示的上下文。origin 应该像 URL 一样格式化,但只包含方案、主机和端口(如有必要),类似于 URL 对象的 url.origin 属性的值。最重要的是,该字符串应省略末尾的斜杠,因为斜杠表示路径。默认值: ''
    • codeGeneration <Object>
      • strings <boolean> 如果设置为 false,则对 eval 或函数构造器(FunctionGeneratorFunction 等)的任何调用都会抛出 EvalError默认值: true
      • wasm <boolean> 如果设置为 false,任何尝试编译 WebAssembly 模块的操作都会抛出 WebAssembly.CompileError默认值: true
    • microtaskMode <string> 如果设置为 afterEvaluate,微任务(通过 Promiseasync function 调度的任务)将在脚本执行完 script.runInContext() 后立即运行。在这种情况下,它们包含在 timeoutbreakOnSigint 的作用域中。
  • 返回:<Object> 已上下文化的对象。

如果提供了 contextObjectvm.createContext() 方法将 准备那个对象,以便可以在调用 vm.runInContext()script.runInContext() 时使用。在这样的脚本内部,contextObject 将成为全局对象,保留其所有现有属性,同时还拥有任何标准 全局对象 所具备的内置对象和函数。在 vm 模块运行的脚本之外,全局变量将保持不变。

【If given a contextObject, the vm.createContext() method will prepare that object so that it can be used in calls to vm.runInContext() or script.runInContext(). Inside such scripts, the contextObject will be the global object, 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.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,可以看到所提供的上下文的 nameorigin

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