new vm.SourceTextModule(code[, options])


  • code <string> JavaScript 模块解析代码
  • options
    • identifier <string> 用于堆栈跟踪的字符串。 默认值: 'vm:module(i)',其中 i 是上下文相关的递增索引。
    • cachedData <Buffer> | <TypedArray> | <DataView> 提供一个可选的 BufferTypedArrayDataView,包含 V8 为所提供源代码生成的代码缓存数据。code 必须与创建此 cachedData 的模块相同。
    • context <Object> 情境化 对象,由 vm.createContext() 方法返回,用于在其中编译和评估此 Module。如果未指定上下文,则模块将在当前执行上下文中评估。
    • lineOffset <integer> 指定在此 Module 生成的堆栈跟踪中显示的行号偏移量。默认值: 0
    • columnOffset <integer> 指定此 Module 生成的堆栈跟踪中显示的首行列号偏移。默认值: 0
    • initializeImportMeta <Function> 在评估此 Module 时被调用,用于初始化 import.meta
    • importModuleDynamically <Function> 用于指定在调用 import() 时本模块在评估期间应如何加载模块。此选项是实验性模块 API 的一部分。我们不建议在生产环境中使用它。详细信息请参见 在编译 API 中支持动态 import()

创建一个新的 SourceTextModule 实例。

【Creates a new SourceTextModule instance.】

分配给 import.meta 对象的属性如果是对象,可能允许模块访问指定 context 之外的信息。使用 vm.runInContext() 可以在特定上下文中创建对象。

【Properties assigned to the import.meta object that are objects may allow the module to access information outside the specified context. Use vm.runInContext() to create objects in a specific context.】

import vm from 'node:vm';

const contextifiedObject = vm.createContext({ secret: 42 });

const module = new vm.SourceTextModule(
  'Object.getPrototypeOf(import.meta.prop).secret = secret;',
  {
    initializeImportMeta(meta) {
      // Note: this object is created in the top context. As such,
      // Object.getPrototypeOf(import.meta.prop) points to the
      // Object.prototype in the top context rather than that in
      // the contextified object.
      meta.prop = {};
    },
  });
// The module has an empty `moduleRequests` array.
module.linkRequests([]);
module.instantiate();
await module.evaluate();

// Now, Object.prototype.secret will be equal to 42.
//
// To fix this problem, replace
//     meta.prop = {};
// above with
//     meta.prop = vm.runInContext('{}', contextifiedObject);const vm = require('node:vm');
const contextifiedObject = vm.createContext({ secret: 42 });
(async () => {
  const module = new vm.SourceTextModule(
    'Object.getPrototypeOf(import.meta.prop).secret = secret;',
    {
      initializeImportMeta(meta) {
        // Note: this object is created in the top context. As such,
        // Object.getPrototypeOf(import.meta.prop) points to the
        // Object.prototype in the top context rather than that in
        // the contextified object.
        meta.prop = {};
      },
    });
  // The module has an empty `moduleRequests` array.
  module.linkRequests([]);
  module.instantiate();
  await module.evaluate();
  // Now, Object.prototype.secret will be equal to 42.
  //
  // To fix this problem, replace
  //     meta.prop = {};
  // above with
  //     meta.prop = vm.runInContext('{}', contextifiedObject);
})();