Customization Hooks
History
initialize hook to replace globalPreload.getFormat, getSource, transformSource, and globalPreload; added load hook and getGlobalPreload hook.Node.js currently supports two types of module customization hooks:
module.registerHooks(options): takes synchronous hook functions that are run directly on the thread where the modules are loaded.module.register(specifier[, parentURL][, options]): takes specifier to a module that exports asynchronous hook functions. The functions are run on a separate loader thread.
The asynchronous hooks incur extra overhead from inter-thread communication,
and have several caveats especially
when customizing CommonJS modules in the module graph.
In most cases, it's recommended to use synchronous hooks via module.registerHooks()
for simplicity.
To register synchronous customization hooks, use module.registerHooks(), which
takes synchronous 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 synchronous 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 synchronous 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 currently only available for synchronous hooks registered via registerHooks(), not for asynchronous
hooks registered via module.register().
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 synchronous 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. }
Synchronous hooks are run in the same thread and the same realm where the modules are loaded, the code in the hook function can pass values to the modules being referenced directly via global variables or other shared states.
Unlike the asynchronous hooks, the synchronous hooks are not inherited into child worker
threads by default, though 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.
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 });
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 util.TextDecoder.
The asynchronous customization hooks have many caveats and it is uncertain if their
issues can be resolved. Users are encouraged to use the synchronous customization hooks
via module.registerHooks() instead to avoid these caveats.
- Asynchronous hooks run on a separate thread, so the hook functions cannot directly mutate the global state of the modules being customized. It's typical to use message channels and atomics to pass data between the two or to affect control flows. See Communication with asynchronous module customization hooks.
- Asynchronous hooks do not affect all
require()calls in the module graph.- Custom
requirefunctions created usingmodule.createRequire()are not affected. - If the asynchronous
loadhook does not override thesourcefor CommonJS modules that go through it, the child modules loaded by those CommonJS modules via built-inrequire()would not be affected by the asynchronous hooks either.
- Custom
- There are several caveats that the asynchronous hooks need to handle when
customizing CommonJS modules. See asynchronous
resolvehook and asynchronousloadhook for details. - When
require()calls inside CommonJS modules are customized by asynchronous hooks, Node.js may need to load the source code of the CommonJS module multiple times to maintain compatibility with existing CommonJS monkey-patching. If the module code changes between loads, this may lead to unexpected behaviors.- As a side effect, if both asynchronous hooks and synchronous hooks are registered and the
asynchronous hooks choose to customize the CommonJS module, the synchronous hooks may be
invoked multiple times for the
require()calls in that CommonJS module.
- As a side effect, if both asynchronous hooks and synchronous hooks are registered and the
asynchronous hooks choose to customize the CommonJS module, the synchronous hooks may be
invoked multiple times for the
Asynchronous customization hooks are registered using module.register() which takes
a path or URL to another module that exports the asynchronous hook functions.
Similar to registerHooks(), register() can be called in a module preloaded by --import or
--require, or called directly within the entry point.
// Use module.register() to register asynchronous hooks in a dedicated thread. import { register } from 'node:module'; register('./hooks.mjs', import.meta.url); // If my-app.mjs is loaded statically here as `import './my-app.mjs'`, since ESM // dependencies are evaluated before the module that imports them, // it's loaded _before_ the hooks are registered above and won't be affected. // To ensure the hooks are applied, dynamic import() must be used to load ESM // after the hooks are registered. import('./my-app.mjs');
const { register } = require('node:module'); const { pathToFileURL } = require('node:url'); // Use module.register() to register asynchronous hooks in a dedicated thread. register('./hooks.mjs', pathToFileURL(__filename)); import('./my-app.mjs');
In hooks.mjs:
// hooks.mjs export async function resolve(specifier, context, nextResolve) { /* implementation */ } export async function load(url, context, nextLoad) { /* implementation */ }
Unlike synchronous hooks, the asynchronous hooks would not run for these modules loaded in the file
that calls register():
// register-hooks.js import { register, createRequire } from 'node:module'; register('./hooks.mjs', import.meta.url); // Asynchronous hooks does not affect modules loaded via custom require() // functions created by module.createRequire(). const userRequire = createRequire(import.meta.filename); userRequire('./my-app-2.cjs'); // Hooks won't affect this
// register-hooks.js const { register, createRequire } = require('node:module'); const { pathToFileURL } = require('node:url'); register('./hooks.mjs', pathToFileURL(__filename)); // Asynchronous hooks does not affect modules loaded via built-in require() // in the module calling `register()` require('./my-app-2.cjs'); // Hooks won't affect this // .. or custom require() functions created by module.createRequire(). const userRequire = createRequire(__filename); userRequire('./my-app-3.cjs'); // Hooks won't affect this
Asynchronous hooks can also be registered using a data: URL with the --import flag:
node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register("my-instrumentation", pathToFileURL("./"));' ./my-app.js
Chaining of register() work similarly to registerHooks(). If synchronous and asynchronous
hooks are mixed, the synchronous hooks are always run first before the asynchronous
hooks start running, that is, in the last synchronous hook being run, its next
hook includes invocation of the asynchronous hooks.
// entrypoint.mjs import { register } from 'node:module'; register('./foo.mjs', import.meta.url); register('./bar.mjs', import.meta.url); await import('./my-app.mjs');
// entrypoint.cjs const { register } = require('node:module'); const { pathToFileURL } = require('node:url'); const parentURL = pathToFileURL(__filename); register('./foo.mjs', parentURL); register('./bar.mjs', parentURL); import('./my-app.mjs');
If foo.mjs and bar.mjs define a resolve hook, they will be called like so
(note the right-to-left, starting with ./bar.mjs, then ./foo.mjs, then the Node.js default):
Node.js default ← ./foo.mjs ← ./bar.mjs
When using the asynchronous hooks, the registered hooks also affect subsequent
register calls, which takes care of loading hook modules. In the example above,
bar.mjs will be resolved and loaded via the hooks registered by foo.mjs
(because foo's hooks will have already been added to the chain). This allows
for things like writing hooks in non-JavaScript languages, so long as
earlier registered hooks transpile into JavaScript.
The register() method cannot be called from the thread running the hook module that
exports the asynchronous hooks or its dependencies.
Asynchronous hooks run on a dedicated thread, separate from the main thread that runs application code. This means mutating global variables won't affect the other thread(s), and message channels must be used to communicate between the threads.
The register method can be used to pass data to an initialize hook. The
data passed to the hook may include transferable objects like ports.
import { register } from 'node:module'; import { MessageChannel } from 'node:worker_threads'; // This example demonstrates how a message channel can be used to // communicate with the hooks, by sending `port2` to the hooks. const { port1, port2 } = new MessageChannel(); port1.on('message', (msg) => { console.log(msg); }); port1.unref(); register('./my-hooks.mjs', { parentURL: import.meta.url, data: { number: 1, port: port2 }, transferList: [port2], });
const { register } = require('node:module'); const { pathToFileURL } = require('node:url'); const { MessageChannel } = require('node:worker_threads'); // This example showcases how a message channel can be used to // communicate with the hooks, by sending `port2` to the hooks. const { port1, port2 } = new MessageChannel(); port1.on('message', (msg) => { console.log(msg); }); port1.unref(); register('./my-hooks.mjs', { parentURL: pathToFileURL(__filename), data: { number: 1, port: port2 }, transferList: [port2], });
The register method can be used to register a module that exports a set of
hooks. The hooks are functions that are called by Node.js to customize the
module resolution and loading process. The exported functions must have specific
names and signatures, and they must be exported as named exports.
export async function initialize({ number, port }) { // Receives data from `register`. } export async function resolve(specifier, context, nextResolve) { // Take an `import` or `require` specifier and resolve it to a URL. } export async function load(url, context, nextLoad) { // Take a resolved URL and return the source code to be evaluated. }
Asynchronous hooks are run in a separate thread, isolated from the main thread where
application code runs. That means it is a different realm. The hooks thread
may be terminated by the main thread at any time, so do not depend on
asynchronous operations (like console.log) to complete. They are inherited into
child workers by default.
initialize(): void
anyregister(loader, import.meta.url, { data }).The initialize hook is only accepted by register. registerHooks() does
not support nor need it since initialization done for synchronous hooks can be run
directly before the call to registerHooks().
The initialize hook provides a way to define a custom function that runs in
the hooks thread when the hooks module is initialized. Initialization happens
when the hooks module is registered via register.
This hook can receive data from a register invocation, including
ports and other transferable objects. The return value of initialize can be a
Promise, in which case it will be awaited before the main application thread
execution resumes.
Module customization code:
// path-to-my-hooks.js export async function initialize({ number, port }) { port.postMessage(`increment: ${number + 1}`); }
Caller code:
import assert from 'node:assert'; import { register } from 'node:module'; import { MessageChannel } from 'node:worker_threads'; // This example showcases how a message channel can be used to communicate // between the main (application) thread and the hooks running on the hooks // thread, by sending `port2` to the `initialize` hook. const { port1, port2 } = new MessageChannel(); port1.on('message', (msg) => { assert.strictEqual(msg, 'increment: 2'); }); port1.unref(); register('./path-to-my-hooks.js', { parentURL: import.meta.url, data: { number: 1, port: port2 }, transferList: [port2], });
const assert = require('node:assert'); const { register } = require('node:module'); const { pathToFileURL } = require('node:url'); const { MessageChannel } = require('node:worker_threads'); // This example showcases how a message channel can be used to communicate // between the main (application) thread and the hooks running on the hooks // thread, by sending `port2` to the `initialize` hook. const { port1, port2 } = new MessageChannel(); port1.on('message', (msg) => { assert.strictEqual(msg, 'increment: 2'); }); port1.unref(); register('./path-to-my-hooks.js', { parentURL: pathToFileURL(__filename), data: { number: 1, port: port2 }, transferList: [port2], });
Asynchronous resolve(specifier, context, nextResolve)
History
context.importAssertions is replaced with context.importAttributes. Using the old name is still supported and will emit an experimental warning.nextResolve() or include a shortCircuit property set to true in its return.stringObjectFunctionresolve hook in the chain, or the
Node.js default resolve hook after the last user-supplied resolve hookPromise that will resolve to such an object.load 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 asynchronous version works similarly to the synchronous version, only that the
nextResolve function returns a Promise, and the resolve hook itself can return a Promise.
Warning In the case of the asynchronous version, despite support for returning promises and async functions, calls to
resolvemay still block the main thread which can impact performance.
Warning The
resolvehook invoked forrequire()calls inside CommonJS modules customized by asynchronous hooks does not receive the original specifier passed torequire(). Instead, it receives a URL already fully resolved using the default CommonJS resolution.
Warning In the CommonJS modules that are customized by the asynchronous customization hooks,
require.resolve()andrequire()will use"import"export condition instead of"require", which may cause unexpected behaviors when loading dual packages.
export async function resolve(specifier, context, nextResolve) { // When calling `defaultResolve`, the arguments can be modified. For example, // to change the specifier or add conditions. if (specifier.includes('foo')) { specifier = specifier.replace('foo', 'bar'); return nextResolve(specifier, { ...context, conditions: [...context.conditions, 'another-condition'], }); } // The hook can also skips 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 not calling nextResolve(). }; } // 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); }
stringresolve chainObjectFunctionload hook in the chain, or the
Node.js default load hook after the last user-supplied load hookPromisePromise that will resolve to such an object.stringload hooks. Default: falsestring | ArrayBuffer | TypedArrayWarning: The asynchronous
loadhook and namespaced exports from CommonJS modules are incompatible. Attempting to use them together will result in an empty object from the import. This may be addressed in the future. This does not apply to the synchronousloadhook, in which case exports can be used as usual.
The asynchronous version works similarly to the synchronous version, though
when using the asynchronous load hook, omitting vs providing a source for
'commonjs' has very different effects:
- When a
sourceis provided, allrequirecalls from this module will be processed by the ESM loader with registeredresolveandloadhooks; allrequire.resolvecalls from this module will be processed by the ESM loader with registeredresolvehooks; only a subset of the CommonJS API will be available (e.g. norequire.extensions, norequire.cache, norequire.resolve.paths) and monkey-patching on the CommonJS module loader will not apply. - If
sourceis undefined ornull, it will be handled by the CommonJS module loader andrequire/require.resolvecalls will not go through the registered hooks. This behavior for nullishsourceis temporary — in the future, nullishsourcewill not be supported.
These caveats do not apply to the synchronous load hook, in which case
the complete set of CommonJS APIs available to the customized CommonJS
modules, and require/require.resolve always go through the registered
hooks.
The Node.js internal asynchronous load implementation, which is the value of next for the
last hook in the load chain, returns null for source when format is
'commonjs' for backward compatibility. Here is an example hook that would
opt-in to using the non-default behavior:
import { readFile } from 'node:fs/promises'; // Asynchronous version accepted by module.register(). This fix is not needed // for the synchronous version accepted by module.registerHooks(). export async function load(url, context, nextLoad) { const result = await nextLoad(url, context); if (result.format === 'commonjs') { result.source ??= await readFile(new URL(result.responseURL ?? url)); } return result; }
This doesn't apply to the synchronous load hook either, in which case the
source returned contains source code loaded by the next hook, regardless
of module format.
The various module customization hooks can be used together to accomplish wide-ranging customizations of the Node.js code loading and evaluation behaviors.
The hook below registers hooks to enable rudimentary support for such specifiers. While this may seem like a significant improvement to Node.js core functionality, there are substantial downsides to actually using these hooks: performance is much slower than loading files from disk, there is no caching, and there is no security.
// https-hooks.mjs import { get } from 'node:https'; export function load(url, context, nextLoad) { // For JavaScript to be loaded over the network, we need to fetch and // return it. if (url.startsWith('https://')) { return new Promise((resolve, reject) => { get(url, (res) => { let data = ''; res.setEncoding('utf8'); res.on('data', (chunk) => data += chunk); res.on('end', () => resolve({ // This example assumes all network-provided JavaScript is ES module // code. format: 'module', shortCircuit: true, source: data, })); }).on('error', (err) => reject(err)); }); } // Let Node.js handle all other URLs. return nextLoad(url); }
// main.mjs import { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js'; console.log(VERSION);
With the preceding hooks module, running
node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./https-hooks.mjs"));' ./main.mjs
prints the current version of CoffeeScript per the module at the URL in
main.mjs.
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-hooks.mjs import { readFile } from 'node:fs/promises'; import { findPackageJSON } from 'node:module'; import coffeescript from 'coffeescript'; const extensionsRegex = /\.(coffee|litcoffee|coffee\.md)$/; export async function load(url, context, nextLoad) { if (extensionsRegex.test(url)) { // CoffeeScript files can be either CommonJS or ES modules. Use a custom format // to tell Node.js not to detect its module type. const { source: rawSource } = await nextLoad(url, { ...context, format: 'coffee' }); // This hook converts CoffeeScript source code into JavaScript source code // for all imported CoffeeScript files. const transformedSource = coffeescript.compile(rawSource.toString(), url); // To determine how Node.js would interpret the transpilation result, // search up the file system for the nearest parent package.json file // and read its "type" field. return { format: await getPackageType(url), shortCircuit: true, source: transformedSource, }; } // Let Node.js handle all other URLs. return nextLoad(url, context); } async function getPackageType(url) { // `url` is only a file path during the first iteration when passed the // resolved url from the load() hook // an actual file path from load() will contain a file extension as it's // required by the spec // this simple truthy check for whether `url` contains a file extension will // work for most projects but does not cover some edge-cases (such as // extensionless files or a url ending in a trailing space) const pJson = findPackageJSON(url); return readFile(pJson, 'utf8') .then(JSON.parse) .then((json) => json?.type) .catch(() => undefined); }
// 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 modules, running
node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./coffeescript-hooks.mjs"));' ./main.coffee
or 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-hooks.js import fs from 'node:fs/promises'; const { imports } = JSON.parse(await fs.readFile('import-map.json')); export async function resolve(specifier, context, nextResolve) { if (Object.hasOwn(imports, specifier)) { return nextResolve(imports[specifier], context); } return nextResolve(specifier, context); }
// 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 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./import-map-hooks.js"));' main.js
or node --import ./import-map-sync-hooks.js main.js
should print some module!.