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); })();
new vm.SyntheticModule(exportNames, evaluateCallback, options?): vm.SyntheticModule
Attributes
exportNames:
string[]Array of names that will be exported from the
module.
evaluateCallback:
FunctionCalled when the module is evaluated.
options:
identifier?:
stringString used in stack traces.
Default:
'vm:module(i)' where i is a context-specific ascending
index.context:
ObjectThe 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.
M
syntheticModule.setExport
History
Added in: v13.0.0, v12.16.0
v13.0.0, v12.16.0
No longer need to call
syntheticModule.link() before calling this method.v24.8.0, v22.21.0
syntheticModule.setExport(name, value): void
Attributes
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); })();