On this page

C

vm.SyntheticModule

History
class vm.SyntheticModule extends vm.Module
Stability: 1Experimental

This feature is only available with the --experimental-vm-modules command flag enabled.

The vm.SyntheticModule class provides the Synthetic Module Record as defined in the WebIDL specification. The purpose of synthetic modules is to provide a generic interface for exposing non-JavaScript sources to ECMAScript module graphs.

import { SyntheticModule } from 'node:vm';

const source = '{ "a": 1 }';
const syntheticModule = new SyntheticModule(['default'], function() {
  const obj = JSON.parse(source);
  this.setExport('default', obj);
});

// Use `syntheticModule` in linking
(async () => {
  await syntheticModule.link(() => {});
  await syntheticModule.evaluate();

  console.log('Default export:', syntheticModule.namespace.default);
})();
const { SyntheticModule } = require('node:vm');

const source = '{ "a": 1 }';
const syntheticModule = new SyntheticModule(['default'], function() {
  const obj = JSON.parse(source);
  this.setExport('default', obj);
});

// Use `syntheticModule` in linking
(async () => {
  await syntheticModule.link(() => {});
  await syntheticModule.evaluate();

  console.log('Default export:', syntheticModule.namespace.default);
})();
C

vm.SyntheticModule Constructor

History
new vm.SyntheticModule(exportNames, evaluateCallback, options?): vm.SyntheticModule
Attributes
exportNames:string[]
Array of names that will be exported from the module.
evaluateCallback:Function
Called when the module is evaluated.
options:
identifier?:string
String used in stack traces. Default: 'vm:module(i)' where i is a context-specific ascending index.
context:Object
The contextified object as returned by the vm.createContext() method, to compile and evaluate this Module in.

Creates a new SyntheticModule instance.

Objects assigned to the exports of this instance may allow importers of the module to access information outside the specified context. Use vm.runInContext() to create objects in a specific context.

syntheticModule.setExport(name, value): void
Attributes
name:string
Name of the export to set.
value:any
The value to set the export to.

This method sets the module export binding slots with the given value.

import vm from 'node:vm';

const m = new vm.SyntheticModule(['x'], () => {
  m.setExport('x', 1);
});

await m.evaluate();

assert.strictEqual(m.namespace.x, 1);
const vm = require('node:vm');
(async () => {
  const m = new vm.SyntheticModule(['x'], () => {
    m.setExport('x', 1);
  });
  await m.evaluate();
  assert.strictEqual(m.namespace.x, 1);
})();