node/test/module-hooks/test-module-hooks-resolve-load-builtin-redirect.js
Joyee Cheung 28f468a615
module: fix sync resolve hooks for require with node: prefixes
Previously, when require()-ing builtins with the node: prefix,
the sync resolve hooks were not properly invoked, and load hooks
could not override the builtin's format. This fixes the
handling and enables redirecting prefixed built-ins to on-disk
files and overriding them with other module types via hooks.

PR-URL: https://github.com/nodejs/node/pull/61088
Fixes: https://github.com/nodejs/node/issues/60005
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com>
2025-12-22 14:35:45 +00:00

28 lines
859 B
JavaScript

'use strict';
// This tests the interaction between resolve and load hooks for builtins.
const common = require('../common');
const assert = require('assert');
const { registerHooks } = require('module');
// Pick a builtin that's unlikely to be loaded already - like zlib or dns.
assert(!process.moduleLoadList.includes('NativeModule zlib'));
assert(!process.moduleLoadList.includes('NativeModule dns'));
registerHooks({
resolve: common.mustCall(function resolve(specifier, context, nextResolve) {
assert.strictEqual(specifier, 'dns');
return {
url: 'node:zlib',
shortCircuit: true,
};
}),
load: common.mustCall(function load(url, context, nextLoad) {
assert.strictEqual(url, 'node:zlib');
return nextLoad(url, context);
}),
});
const zlib = require('dns');
assert.strictEqual(typeof zlib.createGzip, 'function');