Customization Hooks
History
initialize hook to replace globalPreload.getFormat, getSource, transformSource, and globalPreload; added load hook and getGlobalPreload hook.Node.js supports module customization hooks registered with
module.registerHooks().
To register customization hooks, use module.registerHooks(), which
takes hook functions directly in-line.
// register-hooks.js import { registerHooks } from 'node:module'; registerHooks({ resolve(specifier, context, nextResolve) { /* implementation */ }, load(url, context, nextLoad) { /* implementation */ }, });
// register-hooks.js const { registerHooks } = require('node:module'); registerHooks({ resolve(specifier, context, nextResolve) { /* implementation */ }, load(url, context, nextLoad) { /* implementation */ }, });
The hooks can be registered before the application code is run by using the
--import or --require flag:
node --import ./register-hooks.js ./my-app.js node --require ./register-hooks.js ./my-app.js
The specifier passed to --import or --require can also come from a package:
node --import some-package/register ./my-app.js node --require some-package/register ./my-app.js
Where some-package has an "exports" field defining the /register
export to map to a file that calls registerHooks(), like the
register-hooks.js examples above.
Using --import or --require ensures that the hooks are registered before any
application code is loaded, including the entry point of the application and for
any worker threads by default as well.
Alternatively, registerHooks() can be called from the entry point.
If the entry point needs to load other modules and the loading process needs to be
customized, load them using either require() or dynamic import() after the hooks
are registered. Do not use static import statements to load modules that need to be
customized in the same module that registers the hooks, because static import statements
are evaluated before any code in the importer module is run, including the call to
registerHooks(), regardless of where the static import statements appear in the importer
module.
import { registerHooks } from 'node:module'; registerHooks({ /* implementation of hooks */ }); // If loaded using static import, the hooks would not be applied when loading // my-app.mjs, because statically imported modules are all executed before its // importer regardless of where the static import appears. // import './my-app.mjs'; // my-app.mjs must be loaded dynamically to ensure the hooks are applied. await import('./my-app.mjs');
const { registerHooks } = require('node:module'); registerHooks({ /* implementation of hooks */ }); import('./my-app.mjs'); // Or, if my-app.mjs does not have top-level await or it's a CommonJS module, // require() can also be used: // require('./my-app.mjs');
Alternatively, inline JavaScript code can be embedded in data: URLs to register
the hooks before the application code runs. For example,
node --import 'data:text/javascript,import {registerHooks} from "node:module"; registerHooks(/* hooks code */);' ./my-app.js
Hooks are part of a chain, even if that chain consists of only one custom (user-provided) hook and the default hook, which is always present.
Hook functions nest: each one must always return a plain object, and chaining happens
as a result of each function calling next<hookName>(), which is a reference to
the subsequent loader's hook (in LIFO order).
It's possible to call registerHooks() more than once:
// entrypoint.mjs import { registerHooks } from 'node:module'; const hook1 = { /* implementation of hooks */ }; const hook2 = { /* implementation of hooks */ }; // hook2 runs before hook1. registerHooks(hook1); registerHooks(hook2);
// entrypoint.cjs const { registerHooks } = require('node:module'); const hook1 = { /* implementation of hooks */ }; const hook2 = { /* implementation of hooks */ }; // hook2 runs before hook1. registerHooks(hook1); registerHooks(hook2);
In this example, the registered hooks will form chains. These chains run
last-in, first-out (LIFO). If both hook1 and hook2 define a resolve
hook, they will be called like so (note the right-to-left,
starting with hook2.resolve, then hook1.resolve, then the Node.js default):
Node.js default resolve ← hook1.resolve ← hook2.resolve
The same applies to all the other hooks.
A hook that returns a value lacking a required property triggers an exception. A
hook that returns without calling next<hookName>() and without returning
shortCircuit: true also triggers an exception. These errors are to help
prevent unintentional breaks in the chain. Return shortCircuit: true from a
hook to signal that the chain is intentionally ending at your hook.
If a hook should be applied when loading other hook modules, the other hook modules should be loaded after the hook is registered.
The object returned by registerHooks() has a deregister() method that can be
used to remove the hooks from the chain. Once deregister() is called, the hooks
will no longer be invoked during module resolution or loading.
This is available for hooks registered via registerHooks().
import { registerHooks } from 'node:module'; const hooks = registerHooks({ resolve(specifier, context, nextResolve) { console.log('resolve hook called for', specifier); return nextResolve(specifier, context); }, load(url, context, nextLoad) { return nextLoad(url, context); }, }); // At this point, the hooks are active and will be called for // any subsequent import() or require() calls. await import('./my-module.mjs'); // Later, remove the hooks from the chain. hooks.deregister(); // Subsequent loads will no longer trigger the hooks. await import('./another-module.mjs');
const { registerHooks } = require('node:module'); const hooks = registerHooks({ resolve(specifier, context, nextResolve) { console.log('resolve hook called for', specifier); return nextResolve(specifier, context); }, load(url, context, nextLoad) { return nextLoad(url, context); }, }); // At this point, the hooks are active and will be called for // any subsequent require() calls. require('./my-module.cjs'); // Later, remove the hooks from the chain. hooks.deregister(); // Subsequent loads will no longer trigger the hooks. require('./another-module.cjs');
Hook functions accepted by module.registerHooks()
History
The module.registerHooks() method accepts the following hook functions.
function resolve(specifier, context, nextResolve) { // Take an `import` or `require` specifier and resolve it to a URL. } function load(url, context, nextLoad) { // Take a resolved URL and return the source code to be evaluated. }
Hooks are run in the same realm as the modules being loaded, so the code in the hook function can pass values to the modules being referenced directly via global variables or other shared states.
Hooks are not inherited into child worker threads by default. If the hooks are
registered using a file preloaded by --import or --require, child worker threads
can inherit the preloaded scripts via process.execArgv inheritance. See
the documentation of Worker for details.
resolve(specifier, context, nextResolve): Object
stringObjectFunctionresolve hook in the chain, or the
Node.js default resolve hook after the last user-supplied resolve hookObjectload hook (it might be ignored). It can be a
module format (such as 'commonjs' or 'module') or an arbitrary value like 'css' or
'yaml'.resolve hooks. Default: falsestringThe resolve hook chain is responsible for telling Node.js where to find and
how to cache a given import statement or expression, or require call. It can
optionally return a format (such as 'module') as a hint to the load hook. If
a format is specified, the load hook is ultimately responsible for providing
the final format value (and it is free to ignore the hint provided by
resolve); if resolve provides a format, a custom load hook is required
even if only to pass the value to the Node.js default load hook.
Import type attributes are part of the cache key for saving loaded modules into
the internal module cache. The resolve hook is responsible for returning an
importAttributes object if the module should be cached with different
attributes than were present in the source code.
The conditions property in context is an array of conditions that will be used
to match package exports conditions for this resolution
request. They can be used for looking up conditional mappings elsewhere or to
modify the list when calling the default resolution logic.
The current package exports conditions are always in
the context.conditions array passed into the hook. To guarantee default
Node.js module specifier resolution behavior when calling defaultResolve, the
context.conditions array passed to it must include all elements of the
context.conditions array originally passed into the resolve hook.
import { registerHooks } from 'node:module'; function resolve(specifier, context, nextResolve) { // When calling `defaultResolve`, the arguments can be modified. For example, // to change the specifier or to add applicable export conditions. if (specifier.includes('foo')) { specifier = specifier.replace('foo', 'bar'); return nextResolve(specifier, { ...context, conditions: [...context.conditions, 'another-condition'], }); } // The hook can also skip default resolution and provide a custom URL. if (specifier === 'special-module') { return { url: 'file:///path/to/special-module.mjs', format: 'module', shortCircuit: true, // This is mandatory if nextResolve() is not called. }; } // If no customization is needed, defer to the next hook in the chain which would be the // Node.js default resolve if this is the last user-specified loader. return nextResolve(specifier); } registerHooks({ resolve });
load(url, context, nextLoad): Object
stringresolve chainObjectFunctionload hook in the chain, or the
Node.js default load hook after the last user-supplied load hookObjectload hooks. Default: falsestring | ArrayBuffer | TypedArrayThe load hook provides a way to define a custom method for retrieving the
source code of a resolved URL. This would allow a loader to potentially avoid
reading files from disk. It could also be used to map an unrecognized format to
a supported one, for example yaml to module.
import { registerHooks } from 'node:module'; import { Buffer } from 'node:buffer'; function load(url, context, nextLoad) { // The hook can skip default loading and provide a custom source code. if (url === 'special-module') { return { source: 'export const special = 42;', format: 'module', shortCircuit: true, // This is mandatory if nextLoad() is not called. }; } // 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); const source = typeof result.source === 'string' ? result.source : Buffer.from(result.source).toString('utf8'); return { source: source.replace(/foo/g, 'bar'), ...result, }; } registerHooks({ load });
In a more advanced scenario, this can also be used to transform an unsupported source to a supported one (see Examples below).
The final value of format must be one of the following:
format | Description | Acceptable types for source returned by load |
|---|---|---|
'addon' | Load a Node.js addon | null |
'builtin' | Load a Node.js builtin module | null |
'commonjs-typescript' | Load a Node.js CommonJS module with TypeScript syntax | string | ArrayBuffer | TypedArray | null | undefined |
'commonjs' | Load a Node.js CommonJS module | string | ArrayBuffer | TypedArray | null | undefined |
'json' | Load a JSON file | string | ArrayBuffer | TypedArray |
'module-typescript' | Load an ES module with TypeScript syntax | string | ArrayBuffer | TypedArray |
'module' | Load an ES module | string | ArrayBuffer | TypedArray |
'wasm' | Load a WebAssembly module | ArrayBuffer | TypedArray |
The value of source is ignored for format 'builtin' because currently it is
not possible to replace the value of a Node.js builtin (core) module.
These types all correspond to classes defined in ECMAScript.
- The specific
ArrayBufferobject is aSharedArrayBuffer. - The specific
TypedArrayobject is aUint8Array.
If the source value of a text-based format (i.e., 'json', 'module')
is not a string, it is converted to a string using TextDecoder.
The various module customization hooks can be used together to accomplish wide-ranging customizations of the Node.js code loading and evaluation behaviors.
Sources that are in formats Node.js doesn't understand can be converted into
JavaScript using the load hook.
This is less performant than transpiling source files before running Node.js; transpiler hooks should only be used for development and testing purposes.
// coffeescript-sync-hooks.mjs import { readFileSync } from 'node:fs'; import { registerHooks, findPackageJSON } from 'node:module'; import coffeescript from 'coffeescript'; const extensionsRegex = /\.(coffee|litcoffee|coffee\.md)$/; function load(url, context, nextLoad) { if (extensionsRegex.test(url)) { const { source: rawSource } = nextLoad(url, { ...context, format: 'coffee' }); const transformedSource = coffeescript.compile(rawSource.toString(), url); return { format: getPackageType(url), shortCircuit: true, source: transformedSource, }; } return nextLoad(url, context); } function getPackageType(url) { const pJson = findPackageJSON(url); if (!pJson) { return undefined; } try { const file = readFileSync(pJson, 'utf-8'); return JSON.parse(file)?.type; } catch { return undefined; } } registerHooks({ load });
# main.coffee import { scream } from './scream.coffee' console.log scream 'hello, world' import { version } from 'node:process' console.log "Brought to you by Node.js version #{version}"
# scream.coffee export scream = (str) -> str.toUpperCase()
For the sake of running the example, add a package.json file containing the
module type of the CoffeeScript files.
{ "type": "module" }
This is only for running the example. In real world loaders, getPackageType() must be
able to return an format known to Node.js even in the absence of an explicit type in a
package.json, or otherwise the nextLoad call would throw ERR_UNKNOWN_FILE_EXTENSION
(if undefined) or ERR_UNKNOWN_MODULE_FORMAT (if it's not a known format listed in
the load hook documentation).
With the preceding hooks module, running
node --import ./coffeescript-sync-hooks.mjs ./main.coffee
causes main.coffee to be turned into JavaScript after its source code is
loaded from disk but before Node.js executes it; and so on for any .coffee,
.litcoffee or .coffee.md files referenced via import statements of any
loaded file.
The previous two examples defined load hooks. This is an example of a
resolve hook. This hooks module reads an import-map.json file that defines
which specifiers to override to other URLs (this is a very simplistic
implementation of a small subset of the "import maps" specification).
// import-map-sync-hooks.js import fs from 'node:fs/promises'; import module from 'node:module'; const { imports } = JSON.parse(fs.readFileSync('import-map.json', 'utf-8')); function resolve(specifier, context, nextResolve) { if (Object.hasOwn(imports, specifier)) { return nextResolve(imports[specifier], context); } return nextResolve(specifier, context); } module.registerHooks({ resolve });
With these files:
// main.js import 'a-module';
// import-map.json { "imports": { "a-module": "./some-module.js" } }
// some-module.js console.log('some module!');
Running node --import ./import-map-sync-hooks.js main.js
should print some module!.