Modules:node:module
API#
TheModule
object#
Provides general utility methods when interacting with instances ofModule
, themodule
variable often seen inCommonJS modules. Accessedviaimport 'node:module'
orrequire('node:module')
.
module.builtinModules
#
History
Version | Changes |
---|---|
v23.5.0 | The list now also contains prefix-only modules. |
v9.3.0, v8.10.0, v6.13.0 | Added in: v9.3.0, v8.10.0, v6.13.0 |
A list of the names of all modules provided by Node.js. Can be used to verifyif a module is maintained by a third party or not.
module
in this context isn't the same object that's providedby themodule wrapper. To access it, require theModule
module:
// module.mjs// In an ECMAScript moduleimport { builtinModulesas builtin }from'node:module';
// module.cjs// In a CommonJS moduleconst builtin =require('node:module').builtinModules;
module.createRequire(filename)
#
filename
<string> |<URL> Filename to be used to construct the requirefunction. Must be a file URL object, file URL string, or absolute pathstring.- Returns:<require> Require function
import { createRequire }from'node:module';constrequire =createRequire(import.meta.url);// sibling-module.js is a CommonJS module.const siblingModule =require('./sibling-module');
module.findPackageJSON(specifier[, base])
#
specifier
<string> |<URL> The specifier for the module whosepackage.json
toretrieve. When passing abare specifier, thepackage.json
at the root ofthe package is returned. When passing arelative specifier or anabsolute specifier,the closest parentpackage.json
is returned.base
<string> |<URL> The absolute location (file:
URL string or FS path) of thecontaining module. For CJS, use__filename
(not__dirname
!); for ESM, useimport.meta.url
. You do not need to pass it ifspecifier
is anabsolute specifier
.- Returns:<string> |<undefined> A path if the
package.json
is found. Whenspecifier
is a package, the package's rootpackage.json
; when a relative or unresolved, the closestpackage.json
to thespecifier
.
Caveat: Do not use this to try to determine module format. There are many things affectingthat determination; the
type
field of package.json is theleast definitive (ex file extensionsupersedes it, and a loader hook supersedes that).
Caveat: This currently leverages only the built-in default resolver; if
resolve
customization hooks are registered, they will not affect the resolution.This may change in the future.
/path/to/project ├ packages/ ├ bar/ ├ bar.js └ package.json // name = '@foo/bar' └ qux/ ├ node_modules/ └ some-package/ └ package.json // name = 'some-package' ├ qux.js └ package.json // name = '@foo/qux' ├ main.js └ package.json // name = '@foo'
// /path/to/project/packages/bar/bar.jsimport { findPackageJSON }from'node:module';findPackageJSON('..',import.meta.url);// '/path/to/project/package.json'// Same result when passing an absolute specifier instead:findPackageJSON(newURL('../',import.meta.url));findPackageJSON(import.meta.resolve('../'));findPackageJSON('some-package',import.meta.url);// '/path/to/project/packages/bar/node_modules/some-package/package.json'// When passing an absolute specifier, you might get a different result if the// resolved module is inside a subfolder that has nested `package.json`.findPackageJSON(import.meta.resolve('some-package'));// '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json'findPackageJSON('@foo/qux',import.meta.url);// '/path/to/project/packages/qux/package.json'
// /path/to/project/packages/bar/bar.jsconst { findPackageJSON } =require('node:module');const { pathToFileURL } =require('node:url');const path =require('node:path');findPackageJSON('..', __filename);// '/path/to/project/package.json'// Same result when passing an absolute specifier instead:findPackageJSON(pathToFileURL(path.join(__dirname,'..')));findPackageJSON('some-package', __filename);// '/path/to/project/packages/bar/node_modules/some-package/package.json'// When passing an absolute specifier, you might get a different result if the// resolved module is inside a subfolder that has nested `package.json`.findPackageJSON(pathToFileURL(require.resolve('some-package')));// '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json'findPackageJSON('@foo/qux', __filename);// '/path/to/project/packages/qux/package.json'
module.isBuiltin(moduleName)
#
moduleName
<string> name of the module- Returns:<boolean> returns true if the module is builtin else returns false
import { isBuiltin }from'node:module';isBuiltin('node:fs');// trueisBuiltin('fs');// trueisBuiltin('wss');// false
module.register(specifier[, parentURL][, options])
#
History
Version | Changes |
---|---|
v23.6.1, v22.13.1, v20.18.2 | Using this feature with the permission model enabled requires passing |
v20.8.0, v18.19.0 | Add support for WHATWG URL instances. |
v20.6.0, v18.19.0 | Added in: v20.6.0, v18.19.0 |
specifier
<string> |<URL> Customization hooks to be registered; this should bethe same string that would be passed toimport()
, except that if it isrelative, it is resolved relative toparentURL
.parentURL
<string> |<URL> If you want to resolvespecifier
relative to a baseURL, such asimport.meta.url
, you can pass that URL here.Default:'data:'
options
<Object>parentURL
<string> |<URL> If you want to resolvespecifier
relative to abase URL, such asimport.meta.url
, you can pass that URL here. Thisproperty is ignored if theparentURL
is supplied as the second argument.Default:'data:'
data
<any> Any arbitrary, cloneable JavaScript value to pass into theinitialize
hook.transferList
<Object[]>transferable objects to be passed into theinitialize
hook.
Register a module that exportshooks that customize Node.js moduleresolution and loading behavior. SeeCustomization hooks.
This feature requires--allow-worker
if used with thePermission Model.
module.registerHooks(options)
#
options
<Object>load
<Function> |<undefined> Seeload hook.Default:undefined
.resolve
<Function> |<undefined> Seeresolve hook.Default:undefined
.
Registerhooks that customize Node.js module resolution and loading behavior.SeeCustomization hooks.
module.stripTypeScriptTypes(code[, options])
#
code
<string> The code to strip type annotations from.options
<Object>mode
<string>Default:'strip'
. Possible values are:'strip'
Only strip type annotations without performing the transformation of TypeScript features.'transform'
Strip type annotations and transform TypeScript features to JavaScript.
sourceMap
<boolean>Default:false
. Only whenmode
is'transform'
, iftrue
, a source mapwill be generated for the transformed code.sourceUrl
<string> Specifies the source url used in the source map.
- Returns:<string> The code with type annotations stripped.
module.stripTypeScriptTypes()
removes type annotations from TypeScript code. Itcan be used to strip type annotations from TypeScript code before running itwithvm.runInContext()
orvm.compileFunction()
.By default, it will throw an error if the code contains TypeScript featuresthat require transformation such asEnums
,seetype-stripping for more information.When mode is'transform'
, it also transforms TypeScript features to JavaScript,seetransform TypeScript features for more information.When mode is'strip'
, source maps are not generated, because locations are preserved.IfsourceMap
is provided, when mode is'strip'
, an error will be thrown.
WARNING: The output of this function should not be considered stable across Node.js versions,due to changes in the TypeScript parser.
import { stripTypeScriptTypes }from'node:module';const code ='const a: number = 1;';const strippedCode =stripTypeScriptTypes(code);console.log(strippedCode);// Prints: const a = 1;
const { stripTypeScriptTypes } =require('node:module');const code ='const a: number = 1;';const strippedCode =stripTypeScriptTypes(code);console.log(strippedCode);// Prints: const a = 1;
IfsourceUrl
is provided, it will be used appended as a comment at the end of the output:
import { stripTypeScriptTypes }from'node:module';const code ='const a: number = 1;';const strippedCode =stripTypeScriptTypes(code, {mode:'strip',sourceUrl:'source.ts' });console.log(strippedCode);// Prints: const a = 1\n\n//# sourceURL=source.ts;
const { stripTypeScriptTypes } =require('node:module');const code ='const a: number = 1;';const strippedCode =stripTypeScriptTypes(code, {mode:'strip',sourceUrl:'source.ts' });console.log(strippedCode);// Prints: const a = 1\n\n//# sourceURL=source.ts;
Whenmode
is'transform'
, the code is transformed to #"checkbox" checked aria-label="Show modern ES modules syntax">import { stripTypeScriptTypes }from'node:module';const code =` namespace MathUtil { export const add = (a: number, b: number) => a + b; }`;const strippedCode =stripTypeScriptTypes(code, {mode:'transform',sourceMap:true });console.log(strippedCode);// Prints:// var MathUtil;// (function(MathUtil) {// MathUtil.add = (a, b)=>a + b;// })(MathUtil || (MathUtil = {}));// # sourceMappingURL=data:application/json;base64, ...
const { stripTypeScriptTypes } =require('node:module');const code =` namespace MathUtil { export const add = (a: number, b: number) => a + b; }`;const strippedCode =stripTypeScriptTypes(code, {mode:'transform',sourceMap:true });console.log(strippedCode);// Prints:// var MathUtil;// (function(MathUtil) {// MathUtil.add = (a, b)=>a + b;// })(MathUtil || (MathUtil = {}));// # sourceMappingURL=data:application/json;base64, ...
module.syncBuiltinESMExports()
#
Themodule.syncBuiltinESMExports()
method updates all the live bindings forbuiltinES Modules to match the properties of theCommonJS exports. Itdoes not add or remove exported names from theES Modules.
const fs =require('node:fs');const assert =require('node:assert');const { syncBuiltinESMExports } =require('node:module');fs.readFile = newAPI;delete fs.readFileSync;functionnewAPI() {// ...}fs.newAPI = newAPI;syncBuiltinESMExports();import('node:fs').then((esmFS) => {// It syncs the existing readFile property with the new value assert.strictEqual(esmFS.readFile, newAPI);// readFileSync has been deleted from the required fs assert.strictEqual('readFileSync'in fs,false);// syncBuiltinESMExports() does not remove readFileSync from esmFS assert.strictEqual('readFileSync'in esmFS,true);// syncBuiltinESMExports() does not add names assert.strictEqual(esmFS.newAPI,undefined);});
Module compile cache#
History
Version | Changes |
---|---|
v22.8.0 | add initial JavaScript APIs for runtime access. |
v22.1.0 | Added in: v22.1.0 |
The module compile cache can be enabled either using themodule.enableCompileCache()
method or theNODE_COMPILE_CACHE=dir
environment variable. After it is enabled,whenever Node.js compiles a CommonJS or a ECMAScript Module, it will use on-diskV8 code cache persisted in the specified directory to speed up the compilation.This may slow down the first load of a module graph, but subsequent loads of the same modulegraph may get a significant speedup if the contents of the modules do not change.
To clean up the generated compile cache on disk, simply remove the cache directory. The cachedirectory will be recreated the next time the same directory is used for for compile cachestorage. To avoid filling up the disk with stale cache, it is recommended to use a directoryunder theos.tmpdir()
. If the compile cache is enabled by a call tomodule.enableCompileCache()
without specifying the directory, Node.js will usetheNODE_COMPILE_CACHE=dir
environment variable if it's set, or defaultstopath.join(os.tmpdir(), 'node-compile-cache')
otherwise. To locate the compile cachedirectory used by a running Node.js instance, usemodule.getCompileCacheDir()
.
Currently when using the compile cache withV8 JavaScript code coverage, thecoverage being collected by V8 may be less precise in functions that aredeserialized from the code cache. It's recommended to turn this off whenrunning tests to generate precise coverage.
The enabled module compile cache can be disabled by theNODE_DISABLE_COMPILE_CACHE=1
environment variable. This can be useful when the compile cache leads to unexpected orundesired behaviors (e.g. less precise test coverage).
Compilation cache generated by one version of Node.js can not be reused by a differentversion of Node.js. Cache generated by different versions of Node.js will be storedseparately if the same base directory is used to persist the cache, so they can co-exist.
At the moment, when the compile cache is enabled and a module is loaded afresh, thecode cache is generated from the compiled code immediately, but will only be writtento disk when the Node.js instance is about to exit. This is subject to change. Themodule.flushCompileCache()
method can be used to ensure the accumulated code cacheis flushed to disk in case the application wants to spawn other Node.js instancesand let them share the cache long before the parent exits.
module.constants.compileCacheStatus
#
The following constants are returned as thestatus
field in the object returned bymodule.enableCompileCache()
to indicate the result of the attempt to enable themodule compile cache.
Constant | Description |
---|---|
ENABLED | Node.js has enabled the compile cache successfully. The directory used to store the compile cache will be returned in thedirectory field in the returned object. |
ALREADY_ENABLED | The compile cache has already been enabled before, either by a previous call tomodule.enableCompileCache() , or by theNODE_COMPILE_CACHE=dir environment variable. The directory used to store the compile cache will be returned in thedirectory field in the returned object. |
FAILED | Node.js fails to enable the compile cache. This can be caused by the lack of permission to use the specified directory, or various kinds of file system errors. The detail of the failure will be returned in themessage field in the returned object. |
DISABLED | Node.js cannot enable the compile cache because the environment variableNODE_DISABLE_COMPILE_CACHE=1 has been set. |
module.enableCompileCache([cacheDir])
#
cacheDir
<string> |<undefined> Optional path to specify the directory where the compile cachewill be stored/retrieved.- Returns:<Object>
status
<integer> One of themodule.constants.compileCacheStatus
message
<string> |<undefined> If Node.js cannot enable the compile cache, this containsthe error message. Only set ifstatus
ismodule.constants.compileCacheStatus.FAILED
.directory
<string> |<undefined> If the compile cache is enabled, this contains the directorywhere the compile cache is stored. Only set ifstatus
ismodule.constants.compileCacheStatus.ENABLED
ormodule.constants.compileCacheStatus.ALREADY_ENABLED
.
Enablemodule compile cache in the current Node.js instance.
IfcacheDir
is not specified, Node.js will either use the directory specified by theNODE_COMPILE_CACHE=dir
environment variable if it's set, or usepath.join(os.tmpdir(), 'node-compile-cache')
otherwise. For general use cases, it'srecommended to callmodule.enableCompileCache()
without specifying thecacheDir
,so that the directory can be overridden by theNODE_COMPILE_CACHE
environmentvariable when necessary.
Since compile cache is supposed to be a quiet optimization that is not required for theapplication to be functional, this method is designed to not throw any exception when thecompile cache cannot be enabled. Instead, it will return an object containing an errormessage in themessage
field to aid debugging.If compile cache is enabled successfully, thedirectory
field in the returned objectcontains the path to the directory where the compile cache is stored. Thestatus
field in the returned object would be one of themodule.constants.compileCacheStatus
values to indicate the result of the attempt to enable themodule compile cache.
This method only affects the current Node.js instance. To enable it in child worker threads,either call this method in child worker threads too, or set theprocess.env.NODE_COMPILE_CACHE
value to compile cache directory so the behavior canbe inherited into the child workers. The directory can be obtained either from thedirectory
field returned by this method, or withmodule.getCompileCacheDir()
.
module.flushCompileCache()
#
Flush themodule compile cache accumulated from modules already loadedin the current Node.js instance to disk. This returns after all the flushingfile system operations come to an end, no matter they succeed or not. If thereare any errors, this will fail silently, since compile cache misses should notinterfere with the actual operation of the application.
module.getCompileCacheDir()
#
- Returns:<string> |<undefined> Path to themodule compile cache directory if it is enabled,or
undefined
otherwise.
Customization Hooks#
History
Version | Changes |
---|---|
v23.5.0, v22.15.0 | Add support for synchronous and in-thread hooks. |
v20.6.0, v18.19.0 | Added |
v18.6.0, v16.17.0 | Add support for chaining loaders. |
v16.12.0 | Removed |
v8.8.0 | Added in: v8.8.0 |
There are two types of module customization hooks that are currently supported:
module.register(specifier[, parentURL][, options])
which takes a module thatexports asynchronous hook functions. The functions are run on a separate loaderthread.module.registerHooks(options)
which takes synchronous hook functions that arerun directly on the thread where the module is loaded.
Enabling#
Module resolution and loading can be customized by:
- Registering a file which exports a set of asynchronous hook functions, using the
register
method fromnode:module
, - Registering a set of synchronous hook functions using the
registerHooks
methodfromnode:module
.
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.jsnode --require ./register-hooks.js ./my-app.js
// register-hooks.js// This file can only be require()-ed if it doesn't contain top-level await.// Use module.register() to register asynchronous hooks in a dedicated thread.import { register }from'node:module';register('./hooks.mjs',import.meta.url);
// register-hooks.jsconst { 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));
// Use module.registerHooks() to register synchronous hooks in the main thread.import { registerHooks }from'node:module';registerHooks({resolve(specifier, context, nextResolve) {/* implementation */ },load(url, context, nextLoad) {/* implementation */ },});
// Use module.registerHooks() to register synchronous hooks in the main thread.const { registerHooks } =require('node:module');registerHooks({resolve(specifier, context, nextResolve) {/* implementation */ },load(url, context, nextLoad) {/* implementation */ },});
The file passed to--import
or--require
can also be an export from a dependency:
node --import some-package/register ./my-app.jsnode --require some-package/register ./my-app.js
Wheresome-package
has an"exports"
field defining the/register
export to map to a file that callsregister()
, like the followingregister-hooks.js
example.
Using--import
or--require
ensures that the hooks are registered before anyapplication files are imported, including the entry point of the application and forany worker threads by default as well.
Alternatively,register()
andregisterHooks()
can be called from the entry point,though dynamicimport()
must be used for any ESM code that should be run after the hooksare registered.
import { register }from'node:module';register('http-to-https',import.meta.url);// Because this is a dynamic `import()`, the `http-to-https` hooks will run// to handle `./my-app.js` and any other files it imports or requires.awaitimport('./my-app.js');
const { register } =require('node:module');const { pathToFileURL } =require('node:url');register('http-to-https',pathToFileURL(__filename));// Because this is a dynamic `import()`, the `http-to-https` hooks will run// to handle `./my-app.js` and any other files it imports or requires.import('./my-app.js');
Customization hooks will run for any modules loaded later than the registrationand the modules they reference viaimport
and the built-inrequire
.require
function created by users usingmodule.createRequire()
can only becustomized by the synchronous hooks.
In this example, we are registering thehttp-to-https
hooks, but they willonly be available for subsequently imported modules — in this case,my-app.js
and anything it references viaimport
or built-inrequire
in CommonJS dependencies.
If theimport('./my-app.js')
had instead been a staticimport './my-app.js'
, theapp would havealready been loadedbefore thehttp-to-https
hooks wereregistered. This due to the ES modules specification, where static imports areevaluated from the leaves of the tree first, then back to the trunk. There canbe static importswithinmy-app.js
, which will not be evaluated untilmy-app.js
is dynamically imported.
If synchronous hooks are used, bothimport
,require
and userrequire
createdusingcreateRequire()
are supported.
import { registerHooks, createRequire }from'node:module';registerHooks({/* implementation of synchronous hooks */ });constrequire =createRequire(import.meta.url);// The synchronous hooks affect import, require() and user require() function// created through createRequire().awaitimport('./my-app.js');require('./my-app-2.js');
const { register, registerHooks } =require('node:module');const { pathToFileURL } =require('node:url');registerHooks({/* implementation of synchronous hooks */ });const userRequire =createRequire(__filename);// The synchronous hooks affect import, require() and user require() function// created through createRequire().import('./my-app.js');require('./my-app-2.js');userRequire('./my-app-3.js');
Finally, if all you want to do is register hooks before your app runs and youdon't want to create a separate file for that purpose, you can pass adata:
URL to--import
:
node --import'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register("http-to-https", pathToFileURL("./"));' ./my-app.js
Chaining#
It's possible to callregister
more than once:
// entrypoint.mjsimport { register }from'node:module';register('./foo.mjs',import.meta.url);register('./bar.mjs',import.meta.url);awaitimport('./my-app.mjs');
// entrypoint.cjsconst { 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');
In this example, the registered hooks will form chains. These chains runlast-in, first out (LIFO). If bothfoo.mjs
andbar.mjs
define aresolve
hook, they will be called like so (note the right-to-left):node's default ←./foo.mjs
←./bar.mjs
(starting with./bar.mjs
, then./foo.mjs
, then the Node.js default).The same applies to all the other hooks.
The registered hooks also affectregister
itself. In this example,bar.mjs
will be resolved and loaded via the hooks registered byfoo.mjs
(becausefoo
's hooks will have already been added to the chain). This allowsfor things like writing hooks in non-JavaScript languages, so long asearlier registered hooks transpile into JavaScript.
Theregister
method cannot be called from within the module that defines thehooks.
Chaining ofregisterHooks
work similarly. If synchronous and asynchronoushooks are mixed, the synchronous hooks are always run first before the asynchronoushooks start running, that is, in the last synchronous hook being run, its nexthook includes invocation of the asynchronous hooks.
// entrypoint.mjsimport { registerHooks }from'node:module';const hook1 = {/* implementation of hooks */ };const hook2 = {/* implementation of hooks */ };// hook2 run before hook1.registerHooks(hook1);registerHooks(hook2);
// entrypoint.cjsconst { registerHooks } =require('node:module');const hook1 = {/* implementation of hooks */ };const hook2 = {/* implementation of hooks */ };// hook2 run before hook1.registerHooks(hook1);registerHooks(hook2);
Communication with module customization hooks#
Asynchronous hooks run on a dedicated thread, separate from the mainthread that runs application code. This means mutating global variables won'taffect the other thread(s), and message channels must be used to communicatebetween the threads.
Theregister
method can be used to pass data to aninitialize
hook. Thedata 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 } =newMessageChannel();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 } =newMessageChannel();port1.on('message',(msg) => {console.log(msg);});port1.unref();register('./my-hooks.mjs', {parentURL:pathToFileURL(__filename),data: {number:1,port: port2 },transferList: [port2],});
Synchronous module hooks are run on the same thread where the application code isrun. They can directly mutate the globals of the context accessed by the main thread.
Hooks#
Asynchronous hooks accepted bymodule.register()
#
Theregister
method can be used to register a module that exports a set ofhooks. The hooks are functions that are called by Node.js to customize themodule resolution and loading process. The exported functions must have specificnames and signatures, and they must be exported as named exports.
exportasyncfunctioninitialize({ number, port }) {// Receives data from `register`.}exportasyncfunctionresolve(specifier, context, nextResolve) {// Take an `import` or `require` specifier and resolve it to a URL.}exportasyncfunctionload(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 whereapplication code runs. That means it is a differentrealm. The hooks threadmay be terminated by the main thread at any time, so do not depend onasynchronous operations (likeconsole.log
) to complete. They are inherited intochild workers by default.
Synchronous hooks accepted bymodule.registerHooks()
#
Themodule.registerHooks()
method accepts synchronous hook functions.initialize()
is not supported nor necessary, as the hook implementercan simply run the initialization code directly before the call tomodule.registerHooks()
.
functionresolve(specifier, context, nextResolve) {// Take an `import` or `require` specifier and resolve it to a URL.}functionload(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 samerealm where the modulesare loaded. Unlike the asynchronous hooks they are not inherited into child workerthreads by default, though if the hooks are registered using a file preloaded by--import
or--require
, child worker threads can inherit the preloaded scriptsviaprocess.execArgv
inheritance. Seethe documentation ofWorker
for detail.
In synchronous hooks, users can expectconsole.log()
to complete in the same way thatthey expectconsole.log()
in module code to complete.
Conventions of hooks#
Hooks are part of achain, even if that chain consists of only onecustom (user-provided) hook and the default hook, which is always present. Hookfunctions nest: each one must always return a plain object, and chaining happensas a result of each function callingnext<hookName>()
, which is a reference tothe subsequent loader's hook (in LIFO order).
A hook that returns a value lacking a required property triggers an exception. Ahook that returns without callingnext<hookName>()
and without returningshortCircuit: true
also triggers an exception. These errors are to helpprevent unintentional breaks in the chain. ReturnshortCircuit: true
from ahook to signal that the chain is intentionally ending at your hook.
initialize()
#
data
<any> The data fromregister(loader, import.meta.url, { data })
.
Theinitialize
hook is only accepted byregister
.registerHooks()
doesnot support nor need it since initialization done for synchronous hooks can be rundirectly before the call toregisterHooks()
.
Theinitialize
hook provides a way to define a custom function that runs inthe hooks thread when the hooks module is initialized. Initialization happenswhen the hooks module is registered viaregister
.
This hook can receive data from aregister
invocation, includingports and other transferable objects. The return value ofinitialize
can be a<Promise>, in which case it will be awaited before the main application threadexecution resumes.
Module customization code:
// path-to-my-hooks.jsexportasyncfunctioninitialize({ number, port }) { port.postMessage(`increment:${number +1}`);}
Caller code:
import assertfrom'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 } =newMessageChannel();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 } =newMessageChannel();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],});
resolve(specifier, context, nextResolve)
#
History
Version | Changes |
---|---|
v23.5.0, v22.15.0 | Add support for synchronous and in-thread hooks. |
v21.0.0, v20.10.0, v18.19.0 | The property |
v18.6.0, v16.17.0 | Add support for chaining resolve hooks. Each hook must either call |
v17.1.0, v16.14.0 | Add support for import assertions. |
specifier
<string>context
<Object>conditions
<string[]> Export conditions of the relevantpackage.json
importAttributes
<Object> An object whose key-value pairs represent theattributes for the module to importparentURL
<string> |<undefined> The module importing this one, or undefinedif this is the Node.js entry point
nextResolve
<Function> The subsequentresolve
hook in the chain, or theNode.js defaultresolve
hook after the last user-suppliedresolve
hookspecifier
<string>context
<Object> |<undefined> When omitted, the defaults are provided. When provided, defaultsare merged in with preference to the provided properties.
- Returns:<Object> |<Promise> The asynchronous version takes either an object containing thefollowing properties, or a
Promise
that will resolve to such an object. Thesynchronous version only accepts an object returned synchronously.format
<string> |<null> |<undefined> A hint to theload
hook (it might be ignored). It can be amodule format (such as'commonjs'
or'module'
) or an arbitrary value like'css'
or'yaml'
.importAttributes
<Object> |<undefined> The import attributes to use whencaching the module (optional; if excluded the input will be used)shortCircuit
<undefined> |<boolean> A signal that this hook intends toterminate the chain ofresolve
hooks.Default:false
url
<string> The absolute URL to which this input resolves
Warning In the case of the asynchronous version, despite support for returningpromises and async functions, calls to
resolve
may still block the main thread whichcan impact performance.
Theresolve
hook chain is responsible for telling Node.js where to find andhow to cache a givenimport
statement or expression, orrequire
call. It canoptionally return a format (such as'module'
) as a hint to theload
hook. Ifa format is specified, theload
hook is ultimately responsible for providingthe finalformat
value (and it is free to ignore the hint provided byresolve
); ifresolve
provides aformat
, a customload
hook is requiredeven if only to pass the value to the Node.js defaultload
hook.
Import type attributes are part of the cache key for saving loaded modules intothe internal module cache. Theresolve
hook is responsible for returning animportAttributes
object if the module should be cached with differentattributes than were present in the source code.
Theconditions
property incontext
is an array of conditions that will be usedto matchpackage exports conditions for this resolutionrequest. They can be used for looking up conditional mappings elsewhere or tomodify the list when calling the default resolution logic.
The currentpackage exports conditions are always inthecontext.conditions
array passed into the hook. To guaranteedefaultNode.js module specifier resolution behavior when callingdefaultResolve
, thecontext.conditions
array passed to itmust includeall elements of thecontext.conditions
array originally passed into theresolve
hook.
// Asynchronous version accepted by module.register().exportasyncfunctionresolve(specifier, context, nextResolve) {const { parentURL =null } = context;if (Math.random() >0.5) {// Some condition.// For some or all specifiers, do some custom logic for resolving.// Always return an object of the form {url: <string>}.return {shortCircuit:true,url: parentURL ?newURL(specifier, parentURL).href :newURL(specifier).href, }; }if (Math.random() <0.5) {// Another condition.// When calling `defaultResolve`, the arguments can be modified. In this// case it's adding another value for matching conditional exports.returnnextResolve(specifier, { ...context,conditions: [...context.conditions,'another-condition'], }); }// Defer to the next hook in the chain, which would be the// Node.js default resolve if this is the last user-specified loader.returnnextResolve(specifier);}
// Synchronous version accepted by module.registerHooks().functionresolve(specifier, context, nextResolve) {// Similar to the asynchronous resolve() above, since that one does not have// any asynchronous logic.}
load(url, context, nextLoad)
#
History
Version | Changes |
---|---|
v23.5.0, v22.15.0 | Add support for synchronous and in-thread version. |
v22.6.0 | Add support for |
v20.6.0 | Add support for |
v18.6.0, v16.17.0 | Add support for chaining load hooks. Each hook must either call |
url
<string> The URL returned by theresolve
chaincontext
<Object>conditions
<string[]> Export conditions of the relevantpackage.json
format
<string> |<null> |<undefined> The format optionally supplied by theresolve
hook chain. This can be any string value as an input; input values do not need toconform to the list of acceptable return values described below.importAttributes
<Object>
nextLoad
<Function> The subsequentload
hook in the chain, or theNode.js defaultload
hook after the last user-suppliedload
hookurl
<string>context
<Object> |<undefined> When omitted, defaults are provided. When provided, defaults aremerged in with preference to the provided properties. In the defaultnextLoad
, ifthe module pointed to byurl
does not have explicit module type information,context.format
is mandatory.
- Returns:<Object> |<Promise> The asynchronous version takes either an object containing thefollowing properties, or a
Promise
that will resolve to such an object. Thesynchronous version only accepts an object returned synchronously.format
<string>shortCircuit
<undefined> |<boolean> A signal that this hook intends toterminate the chain ofload
hooks.Default:false
source
<string> |<ArrayBuffer> |<TypedArray> The source for Node.js to evaluate
Theload
hook provides a way to define a custom method of determining how aURL should be interpreted, retrieved, and parsed. It is also in charge ofvalidating the import attributes.
The final value offormat
must be one of the following:
format | Description | Acceptable types forsource returned byload |
---|---|---|
'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 ofsource
is ignored for type'builtin'
because currently it isnot possible to replace the value of a Node.js builtin (core) module.
Caveat in the asynchronousload
hook#
When using the asynchronousload
hook, omitting vs providing asource
for'commonjs'
has very different effects:
- When a
source
is provided, allrequire
calls from this module will beprocessed by the ESM loader with registeredresolve
andload
hooks; allrequire.resolve
calls from this module will be processed by the ESM loaderwith registeredresolve
hooks; only a subset of the CommonJS API will beavailable (e.g. norequire.extensions
, norequire.cache
, norequire.resolve.paths
) and monkey-patching on the CommonJS module loaderwill not apply. - If
source
is undefined ornull
, it will be handled by the CommonJS moduleloader andrequire
/require.resolve
calls will not go through theregistered hooks. This behavior for nullishsource
is temporary — in thefuture, nullishsource
will not be supported.
These caveats do not apply to the synchronousload
hook, in which casethe complete set of CommonJS APIs available to the customized CommonJSmodules, andrequire
/require.resolve
always go through the registeredhooks.
The Node.js internal asynchronousload
implementation, which is the value ofnext
for thelast hook in theload
chain, returnsnull
forsource
whenformat
is'commonjs'
for backward compatibility. Here is an example hook that wouldopt-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().exportasyncfunctionload(url, context, nextLoad) {const result =awaitnextLoad(url, context);if (result.format ==='commonjs') { result.source ??=awaitreadFile(newURL(result.responseURL ?? url)); }return result;}
This doesn't apply to the synchronousload
hook either, in which case thesource
returned contains source code loaded by the next hook, regardlessof module format.
Warning: The asynchronous
load
hook and namespaced exports from CommonJSmodules are incompatible. Attempting to use them together will result in an emptyobject from the import. This may be addressed in the future. This does not applyto the synchronousload
hook, in which case exports can be used as usual.
These types all correspond to classes defined in ECMAScript.
- The specific<ArrayBuffer> object is a<SharedArrayBuffer>.
- The specific<TypedArray> object is a<Uint8Array>.
If the source value of a text-based format (i.e.,'json'
,'module'
)is not a string, it is converted to a string usingutil.TextDecoder
.
Theload
hook provides a way to define a custom method for retrieving thesource code of a resolved URL. This would allow a loader to potentially avoidreading files from disk. It could also be used to map an unrecognized format toa supported one, for exampleyaml
tomodule
.
// Asynchronous version accepted by module.register().exportasyncfunctionload(url, context, nextLoad) {const { format } = context;if (Math.random() >0.5) {// Some condition/* For some or all URLs, do some custom logic for retrieving the source. Always return an object of the form { format: <string>, source: <string|buffer>, }. */return { format,shortCircuit:true,source:'...', }; }// Defer to the next hook in the chain.returnnextLoad(url);}
// Synchronous version accepted by module.registerHooks().functionload(url, context, nextLoad) {// Similar to the asynchronous load() above, since that one does not have// any asynchronous logic.}
In a more advanced scenario, this can also be used to transform an unsupportedsource to a supported one (seeExamples below).
Examples#
The various module customization hooks can be used together to accomplishwide-ranging customizations of the Node.js code loading and evaluationbehaviors.
Import from HTTPS#
The hook below registers hooks to enable rudimentary support for suchspecifiers. While this may seem like a significant improvement to Node.js corefunctionality, 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.mjsimport { get }from'node:https';exportfunctionload(url, context, nextLoad) {// For JavaScript to be loaded over the network, we need to fetch and// return it.if (url.startsWith('https://')) {returnnewPromise((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.returnnextLoad(url);}
// main.mjsimport {VERSION }from'https://coffeescript.org/browser-compiler-modern/coffeescript.js';console.log(VERSION);
With the preceding hooks module, runningnode --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 inmain.mjs
.
Transpilation#
Sources that are in formats Node.js doesn't understand can be converted intoJavaScript using theload
hook.
This is less performant than transpiling source files before running Node.js;transpiler hooks should only be used for development and testing purposes.
Asynchronous version#
// coffeescript-hooks.mjsimport { readFile }from'node:fs/promises';import { findPackageJSON }from'node:module';import coffeescriptfrom'coffeescript';const extensionsRegex =/\.(coffee|litcoffee|coffee\.md)$/;exportasyncfunctionload(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 } =awaitnextLoad(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:awaitgetPackageType(url),shortCircuit:true,source: transformedSource, }; }// Let Node.js handle all other URLs.returnnextLoad(url, context);}asyncfunctiongetPackageType(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);returnreadFile(pJson,'utf8') .then(JSON.parse) .then((json) => json?.type) .catch(() =>undefined);}
Synchronous version#
// coffeescript-sync-hooks.mjsimport { readFileSync }from'node:fs';import { registerHooks, findPackageJSON }from'node:module';import coffeescriptfrom'coffeescript';const extensionsRegex =/\.(coffee|litcoffee|coffee\.md)$/;functionload(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, }; }returnnextLoad(url, context);}functiongetPackageType(url) {const pJson =findPackageJSON(url);if (!pJson) {returnundefined; }try {const file =readFileSync(pJson,'utf-8');returnJSON.parse(file)?.type; }catch {returnundefined; }}registerHooks({ load });
Running hooks#
# main.coffeeimport { 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.coffeeexport scream =(str) -> str.toUpperCase()
For the sake of running the example, add apackage.json
file containing themodule type of the CoffeeScript files.
{"type":"module"}
This is only for running the example. In real world loaders,getPackageType()
must beable to return anformat
known to Node.js even in the absence of an explicit type in apackage.json
, or otherwise thenextLoad
call would throwERR_UNKNOWN_FILE_EXTENSION
(if undefined) orERR_UNKNOWN_MODULE_FORMAT
(if it's not a known format listed intheload hook documentation).
With the preceding hooks modules, runningnode --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./coffeescript-hooks.mjs"));' ./main.coffee
ornode --import ./coffeescript-sync-hooks.mjs ./main.coffee
causesmain.coffee
to be turned into JavaScript after its source code isloaded from disk but before Node.js executes it; and so on for any.coffee
,.litcoffee
or.coffee.md
files referenced viaimport
statements of anyloaded file.
Import maps#
The previous two examples definedload
hooks. This is an example of aresolve
hook. This hooks module reads animport-map.json
file that defineswhich specifiers to override to other URLs (this is a very simplisticimplementation of a small subset of the "import maps" specification).
Asynchronous version#
// import-map-hooks.jsimport fsfrom'node:fs/promises';const { imports } =JSON.parse(await fs.readFile('import-map.json'));exportasyncfunctionresolve(specifier, context, nextResolve) {if (Object.hasOwn(imports, specifier)) {returnnextResolve(imports[specifier], context); }returnnextResolve(specifier, context);}
Synchronous version#
// import-map-sync-hooks.jsimport fsfrom'node:fs/promises';importmodulefrom'node:module';const { imports } =JSON.parse(fs.readFileSync('import-map.json','utf-8'));functionresolve(specifier, context, nextResolve) {if (Object.hasOwn(imports, specifier)) {returnnextResolve(imports[specifier], context); }returnnextResolve(specifier, context);}module.registerHooks({ resolve });
Using the hooks#
With these files:
// main.jsimport'a-module';
// import-map.json{"imports":{"a-module":"./some-module.js"}}
// some-module.jsconsole.log('some module!');
Runningnode --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./import-map-hooks.js"));' main.js
ornode --import ./import-map-sync-hooks.js main.js
should printsome module!
.
Source Map Support#
Node.js supports TC39 ECMA-426Source Map format (it was called Source maprevision 3 format).
The APIs in this section are helpers for interacting with the source mapcache. This cache is populated when source map parsing is enabled andsource map include directives are found in a modules' footer.
To enable source map parsing, Node.js must be run with the flag--enable-source-maps
, or with code coverage enabled by settingNODE_V8_COVERAGE=dir
, or be enabled programmatically viamodule.setSourceMapsSupport()
.
// module.mjs// In an ECMAScript moduleimport { findSourceMap,SourceMap }from'node:module';
// module.cjs// In a CommonJS moduleconst { findSourceMap,SourceMap } =require('node:module');
module.getSourceMapsSupport()
#
- Returns:<Object>
This method returns whether theSource Map v3 support for stacktraces is enabled.
module.findSourceMap(path)
#
path
<string>- Returns:<module.SourceMap> |<undefined> Returns
module.SourceMap
if a sourcemap is found,undefined
otherwise.
path
is the resolved path for the file for which a corresponding source mapshould be fetched.
module.setSourceMapsSupport(enabled[, options])
#
This function enables or disables theSource Map v3 support forstack traces.
It provides same features as launching Node.js process with commandline options--enable-source-maps
, with additional options to alter the support for filesinnode_modules
or generated codes.
Only source maps in JavaScript files that are loaded after source maps has beenenabled will be parsed and loaded. Preferably, use the commandline options--enable-source-maps
to avoid losing track of source maps of modules loadedbefore this API call.
Class:module.SourceMap
#
new SourceMap(payload[, { lineLengths }])
#
History
Version | Changes |
---|---|
v20.5.0 | Add support for |
payload
<Object>lineLengths
<number[]>
Creates a newsourceMap
instance.
payload
is an object with keys matching theSource map format:
file
:<string>version
:<number>sources
:<string[]>sourcesContent
:<string[]>names
:<string[]>mappings
:<string>sourceRoot
:<string>
lineLengths
is an optional array of the length of each line in thegenerated code.
sourceMap.findEntry(lineOffset, columnOffset)
#
lineOffset
<number> The zero-indexed line number offset inthe generated sourcecolumnOffset
<number> The zero-indexed column number offsetin the generated source- Returns:<Object>
Given a line offset and column offset in the generated sourcefile, returns an object representing the SourceMap range in theoriginal file if found, or an empty object if not.
The object returned contains the following keys:
- generatedLine:<number> The line offset of the start of therange in the generated source
- generatedColumn:<number> The column offset of start of therange in the generated source
- originalSource:<string> The file name of the original source,as reported in the SourceMap
- originalLine:<number> The line offset of the start of therange in the original source
- originalColumn:<number> The column offset of start of therange in the original source
- name:<string>
The returned value represents the raw range as it appears in theSourceMap, based on zero-indexed offsets,not 1-indexed line andcolumn numbers as they appear in Error messages and CallSiteobjects.
To get the corresponding 1-indexed line and column numbers from alineNumber and columnNumber as they are reported by Error stacksand CallSite objects, usesourceMap.findOrigin(lineNumber, columnNumber)
sourceMap.findOrigin(lineNumber, columnNumber)
#
lineNumber
<number> The 1-indexed line number of the callsite in the generated sourcecolumnNumber
<number> The 1-indexed column numberof the call site in the generated source- Returns:<Object>
Given a 1-indexedlineNumber
andcolumnNumber
from a call site inthe generated source, find the corresponding call site locationin the original source.
If thelineNumber
andcolumnNumber
provided are not found in anysource map, then an empty object is returned. Otherwise, thereturned object contains the following keys:
- name:<string> |<undefined> The name of the range in thesource map, if one was provided
- fileName:<string> The file name of the original source, asreported in the SourceMap
- lineNumber:<number> The 1-indexed lineNumber of thecorresponding call site in the original source
- columnNumber:<number> The 1-indexed columnNumber of thecorresponding call site in the original source