Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions doc/api/module.md
Original file line number Diff line number Diff line change
Expand Up @@ -1027,11 +1027,11 @@ a supported one, for example `yaml` to `module`.

```mjs
import { registerHooks } from 'node:module';
import { Buffer } from 'node:buffer';
import { TextDecoder } from 'node:util';

function load(url, context, nextLoad) {
// The hook can skip default loading and provide a custom source code.
if (url === 'special-module') {
if (url === 'file:///path/to/special-module.mjs') {
return {
source: 'export const special = 42;',
format: 'module',
Expand All @@ -1042,11 +1042,14 @@ function load(url, context, nextLoad) {
// It's possible to modify the source code loaded by the next - possibly default - step,
// for example, replacing 'foo' with 'bar' in the source code of the module.
const result = nextLoad(url, context);
if (result.source == null || result.format === 'wasm') {
return result;
}
const source = typeof result.source === 'string' ?
result.source : Buffer.from(result.source).toString('utf8');
result.source : new TextDecoder().decode(result.source);
return {
source: source.replace(/foo/g, 'bar'),
...result,
source: source.replace(/foo/g, 'bar'),
};
}

Expand Down Expand Up @@ -1816,7 +1819,7 @@ export async function resolve(specifier, context, nextResolve) {

```mjs
// import-map-sync-hooks.js
import fs from 'node:fs/promises';
import fs from 'node:fs';
import module from 'node:module';

const { imports } = JSON.parse(fs.readFileSync('import-map.json', 'utf-8'));
Expand Down
Loading