Modules:node:module API#
TheModule object#
- Type:<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 |
- Type:<string[]>
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.jsontoretrieve. When passing abare specifier, thepackage.jsonat the root ofthe package is returned. When passing arelative specifier or anabsolute specifier,the closest parentpackage.jsonis 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 ifspecifieris anabsolute specifier.- Returns:<string> |<undefined> A path if the
package.jsonis found. Whenspecifieris a package, the package's rootpackage.json; when a relative or unresolved, the closestpackage.jsonto thespecifier.
Caveat: Do not use this to try to determine module format. There are many things affectingthat determination; the
typefield 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
resolvecustomization 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');// falsemodule.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 resolvespecifierrelative to a baseURL, such asimport.meta.url, you can pass that URL here.Default:'data:'options<Object>parentURL<string> |<URL> If you want to resolvespecifierrelative to abase URL, such asimport.meta.url, you can pass that URL here. Thisproperty is ignored if theparentURLis supplied as the second argument.Default:'data:'data<any> Any arbitrary, cloneable JavaScript value to pass into theinitializehook.transferList<Object[]>transferable objects to be passed into theinitializehook.
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)#
History
| Version | Changes |
|---|---|
| v25.4.0 | Synchronous and in-thread hooks are now release candidate. |
| v23.5.0, v22.15.0 | Added in: v23.5.0, v22.15.0 |
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 whenmodeis'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.IfsourceMapis 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, a ECMAScript Module, or a TypeScript module, it willuse 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 thedirectory, 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().
The enabled module compile cache can be disabled by theNODE_DISABLE_COMPILE_CACHE=1environment variable. This can be useful when the compile cache leads to unexpected orundesired behaviors (e.g. less precise test coverage).
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.
The compile cache layout on disk is an implementation detail and should not berelied upon. The compile cache generated is typically only reusable in the sameversion of Node.js, and should be not assumed to be compatible across differentversions of Node.js.
Portability of the compile cache#
By default, caches are invalidated when the absolute paths of the modules beingcached are changed. To keep the cache working after moving theproject directory, enable portable compile cache. This allows previously compiledmodules to be reused across different directory locations as long as the layout relativeto the cache directory remains the same. This would be done on a best-effort basis. IfNode.js cannot compute the location of a module relative to the cache directory, the modulewill not be cached.
There are two ways to enable the portable mode:
Using the portable option in
module.enableCompileCache():// Non-portable cache (default): cache breaks if project is movedmodule.enableCompileCache({directory:'/path/to/cache/storage/dir' });// Portable cache: cache works after the project is movedmodule.enableCompileCache({directory:'/path/to/cache/storage/dir',portable:true });Setting the environment variable:
NODE_COMPILE_CACHE_PORTABLE=1
Limitations of the compile cache#
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.
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.
module.constants.compileCacheStatus#
History
| Version | Changes |
|---|---|
| v25.4.0 | This feature is no longer experimental. |
| v22.8.0 | Added in: v22.8.0 |
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([options])#
History
| Version | Changes |
|---|---|
| v25.4.0 | This feature is no longer experimental. |
| v25.0.0 | Add |
| v25.0.0 | Rename the unreleased |
| v22.8.0 | Added in: v22.8.0 |
options<string> |<Object> Optional. If a string is passed, it is considered to beoptions.directory.directory<string> Optional. Directory to store the compile cache. If not specified,the directory specified by theNODE_COMPILE_CACHE=direnvironment variablewill be used if it's set, orpath.join(os.tmpdir(), 'node-compile-cache')otherwise.portable<boolean> Optional. Iftrue, enables portable compile cache so thatthe cache can be reused even if the project directory is moved. This is a best-effortfeature. If not specified, it will depend on whether the environment variableNODE_COMPILE_CACHE_PORTABLE=1is set.
- Returns:<Object>
status<integer> One of themodule.constants.compileCacheStatusmessage<string> |<undefined> If Node.js cannot enable the compile cache, this containsthe error message. Only set ifstatusismodule.constants.compileCacheStatus.FAILED.directory<string> |<undefined> If the compile cache is enabled, this contains the directorywhere the compile cache is stored. Only set ifstatusismodule.constants.compileCacheStatus.ENABLEDormodule.constants.compileCacheStatus.ALREADY_ENABLED.
Enablemodule compile cache in the current Node.js instance.
For general use cases, it's recommended to callmodule.enableCompileCache() withoutspecifying theoptions.directory, so that the directory can be overridden by theNODE_COMPILE_CACHE environment variable when necessary.
Since compile cache is supposed to be a optimization that is not mission critical, thismethod is designed to not throw any exception when the compile cache cannot be enabled.Instead, it will return an object containing an error message in themessage field toaid debugging. If compile cache is enabled successfully, thedirectory field in thereturned object contains the path to the directory where the compile cache is stored. Thestatus field in the returned object would be one of themodule.constants.compileCacheStatusvalues 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()#
History
| Version | Changes |
|---|---|
| v25.4.0 | This feature is no longer experimental. |
| v23.0.0, v22.10.0 | Added in: v23.0.0, v22.10.0 |
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()#
History
| Version | Changes |
|---|---|
| v25.4.0 | This feature is no longer experimental. |
| v22.8.0 | Added in: v22.8.0 |
- Returns:<string> |<undefined> Path to themodule compile cache directory if it is enabled,or
undefinedotherwise.
Customization Hooks#
History
| Version | Changes |
|---|---|
| v25.4.0 | Synchronous and in-thread hooks are now release candidate. |
| 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 |
Node.js currently supports two types of module customization hooks:
module.registerHooks(options): takes synchronous hookfunctions that are run directly on the thread where the modules are loaded.module.register(specifier[, parentURL][, options]): takes specifier to amodule that exports asynchronous hook functions. The functions are run on aseparate loader thread.
The asynchronous hooks incur extra overhead from inter-thread communication,and haveseveral caveats especiallywhen customizing CommonJS modules in the module graph.In most cases, it's recommended to use synchronous hooks viamodule.registerHooks()for simplicity.
Synchronous customization hooks#
Registration of synchronous customization hooks#
To register synchronous customization hooks, usemodule.registerHooks(), whichtakessynchronous hook functions directly in-line.
// register-hooks.jsimport { registerHooks }from'node:module';registerHooks({resolve(specifier, context, nextResolve) {/* implementation */ },load(url, context, nextLoad) {/* implementation */ },});// register-hooks.jsconst { registerHooks } =require('node:module');registerHooks({resolve(specifier, context, nextResolve) {/* implementation */ },load(url, context, nextLoad) {/* implementation */ },});
Registering hooks before application code runs with flags#
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.jsThe specifier passed to--import or--require can also come from a package:
node --import some-package/register ./my-app.jsnode --require some-package/register ./my-app.jsWheresome-package has an"exports" field defining the/registerexport to map to a file that callsregisterHooks(), like theregister-hooks.js examples above.
Using--import or--require ensures that the hooks are registered before anyapplication code is loaded, including the entry point of the application and forany worker threads by default as well.
Registering hooks before application code runs programmatically#
Alternatively,registerHooks() can be called from the entry point.
If the entry point needs to load other modules and the loading process needs to becustomized, load them using eitherrequire() or dynamicimport() after the hooksare registered. Do not use staticimport statements to load modules that need to becustomized in the same module that registers the hooks, because staticimport statementsare evaluated before any code in the importer module is run, including the call toregisterHooks(), regardless of where the staticimport statements appear in the importermodule.
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.awaitimport('./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');
Registering hooks before application code runs with adata: URL#
Alternatively, inline JavaScript code can be embedded indata: URLs to registerthe hooks before the application code runs. For example,
node --import'data:text/javascript,import {registerHooks} from "node:module"; registerHooks(/* hooks code */);' ./my-app.jsConvention of hooks and chaining#
Hooks are part of a chain, even if that chain consists of only onecustom (user-provided) hook and the default hook, which is always present.
Hook functions 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).
It's possible to callregisterHooks() more than once:
// entrypoint.mjsimport { registerHooks }from'node:module';const hook1 = {/* implementation of hooks */ };const hook2 = {/* implementation of hooks */ };// hook2 runs before hook1.registerHooks(hook1);registerHooks(hook2);// entrypoint.cjsconst { 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 runlast-in, first-out (LIFO). If bothhook1 andhook2 define aresolvehook, they will be called like so (note the right-to-left,starting withhook2.resolve, thenhook1.resolve, then the Node.js default):
Node.js defaultresolve ←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. 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.
If a hook should be applied when loading other hook modules, the other hookmodules should be loaded after the hook is registered.
Hook functions accepted bymodule.registerHooks()#
Themodule.registerHooks() method accepts the following synchronous hook functions.
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, the code in the hook function can pass values to the modules being referenceddirectly via global variables or other shared states.
Unlike the asynchronous hooks, the synchronous hooks 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 details.
Synchronousresolve(specifier, context, nextResolve)#
History
| Version | Changes |
|---|---|
| v23.5.0, v22.15.0 | Add support for synchronous and in-thread hooks. |
specifier<string>context<Object>conditions<string[]> Export conditions of the relevantpackage.jsonimportAttributes<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 subsequentresolvehook in the chain, or theNode.js defaultresolvehook after the last user-suppliedresolvehookspecifier<string>context<Object> |<undefined> When omitted, the defaults are provided. When provided, defaultsare merged in with preference to the provided properties.
- Returns:<Object>
format<string> |<null> |<undefined> A hint to theloadhook (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 ofresolvehooks.Default:falseurl<string> The absolute URL to which this input resolves
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.
import { registerHooks }from'node:module';functionresolve(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');returnnextResolve(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.returnnextResolve(specifier);}registerHooks({ resolve });Synchronousload(url, context, nextLoad)#
History
| Version | Changes |
|---|---|
| v23.5.0, v22.15.0 | Add support for synchronous and in-thread version. |
url<string> The URL returned by theresolvechaincontext<Object>conditions<string[]> Export conditions of the relevantpackage.jsonformat<string> |<null> |<undefined> The format optionally supplied by theresolvehook 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 subsequentloadhook in the chain, or theNode.js defaultloadhook after the last user-suppliedloadhookurl<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 byurldoes not have explicit module type information,context.formatis mandatory.
- Returns:<Object>
format<string> One of the acceptable module formats listedbelow.shortCircuit<undefined> |<boolean> A signal that this hook intends toterminate the chain ofloadhooks.Default:falsesource<string> |<ArrayBuffer> |<TypedArray> The source for Node.js to evaluate
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.
import { registerHooks }from'node:module';import {Buffer }from'node:buffer';functionload(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({ resolve });In a more advanced scenario, this can also be used to transform an unsupportedsource to a supported one (seeExamples below).
Accepted final formats returned byload#
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 format'builtin' because currently it isnot possible to replace the value of a Node.js builtin (core) module.
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.
Asynchronous customization hooks#
Caveats of asynchronous customization hooks#
The asynchronous customization hooks have many caveats and it is uncertain if theirissues can be resolved. Users are encouraged to use the synchronous customization hooksviamodule.registerHooks() instead to avoid these caveats.
- Asynchronous hooks run on a separate thread, so the hook functions cannot directlymutate the global state of the modules being customized. It's typical to use messagechannels and atomics to pass data between the two or to affect control flows.SeeCommunication with asynchronous module customization hooks.
- Asynchronous hooks do not affect all
require()calls in the module graph.- Custom
requirefunctions created usingmodule.createRequire()are notaffected. - If the asynchronous
loadhook does not override thesourcefor CommonJS modulesthat 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 whencustomizing CommonJS modules. Seeasynchronous
resolvehook andasynchronousloadhook 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 maintaincompatibility with existing CommonJS monkey-patching. If the module code changes betweenloads, this may lead to unexpected behaviors.- As a side effect, if both asynchronous hooks and synchronous hooks are registered and theasynchronous hooks choose to customize the CommonJS module, the synchronous hooks may beinvoked multiple times for the
require()calls in that CommonJS module.
- As a side effect, if both asynchronous hooks and synchronous hooks are registered and theasynchronous hooks choose to customize the CommonJS module, the synchronous hooks may beinvoked multiple times for the
Registration of asynchronous customization hooks#
Asynchronous customization hooks are registered usingmodule.register() which takesa path or URL to another module that exports theasynchronous hook functions.
Similar toregisterHooks(),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');
Inhooks.mjs:
// hooks.mjsexportasyncfunctionresolve(specifier, context, nextResolve) {/* implementation */}exportasyncfunctionload(url, context, nextLoad) {/* implementation */}Unlike synchronous hooks, the asynchronous hooks would not run for these modules loaded in the filethat callsregister():
// register-hooks.jsimport { 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(__filename);userRequire('./my-app-2.cjs');// Hooks won't affect this// register-hooks.jsconst { 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 thisAsynchronous hooks can also be registered using adata: 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.jsChaining of asynchronous customization hooks#
Chaining ofregister() work similarly toregisterHooks(). 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 { 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');
Iffoo.mjs andbar.mjs define aresolve 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 subsequentregister calls, which takes care of loading hook modules. In the example above,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 the thread running the hook module thatexports the asynchronous hooks or its dependencies.
Communication with asynchronous 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],});
Asynchronous hooks accepted bymodule.register()#
History
| Version | Changes |
|---|---|
| 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 |
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.
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],});
Asynchronousresolve(specifier, context, nextResolve)#
History
| Version | Changes |
|---|---|
| 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.jsonimportAttributes<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 subsequentresolvehook in the chain, or theNode.js defaultresolvehook after the last user-suppliedresolvehookspecifier<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
Promisethat will resolve to such an object.format<string> |<null> |<undefined> A hint to theloadhook (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 ofresolvehooks.Default:falseurl<string> The absolute URL to which this input resolves
The asynchronous version works similarly to the synchronous version, only that thenextResolve function returns aPromise, and theresolve hook itself can return aPromise.
Warning In the case of the asynchronous version, despite support for returningpromises and async functions, calls to
resolvemay still block the main thread whichcan impact performance.
Warning The
resolvehook invoked forrequire()calls inside CommonJS modulescustomized by asynchronous hooks does not receive the original specifier passed torequire(). Instead, it receives a URL already fully resolved using the defaultCommonJS 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.
exportasyncfunctionresolve(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');returnnextResolve(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.returnnextResolve(specifier);}Asynchronousload(url, context, nextLoad)#
History
| Version | Changes |
|---|---|
| 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 theresolvechaincontext<Object>conditions<string[]> Export conditions of the relevantpackage.jsonformat<string> |<null> |<undefined> The format optionally supplied by theresolvehook 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 subsequentloadhook in the chain, or theNode.js defaultloadhook after the last user-suppliedloadhookurl<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 byurldoes not have explicit module type information,context.formatis mandatory.
- Returns:<Promise> The asynchronous version takes either an object containing thefollowing properties, or a
Promisethat will resolve to such an object.format<string>shortCircuit<undefined> |<boolean> A signal that this hook intends toterminate the chain ofloadhooks.Default:falsesource<string> |<ArrayBuffer> |<TypedArray> The source for Node.js to evaluate
Warning: The asynchronous
loadhook 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 synchronousloadhook, in which case exports can be used as usual.
The asynchronous version works similarly to the synchronous version, thoughwhen using the asynchronousload hook, omitting vs providing asource for'commonjs' has very different effects:
- When a
sourceis provided, allrequirecalls from this module will beprocessed by the ESM loader with registeredresolveandloadhooks; allrequire.resolvecalls from this module will be processed by the ESM loaderwith registeredresolvehooks; 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
sourceis undefined ornull, it will be handled by the CommonJS moduleloader andrequire/require.resolvecalls will not go through theregistered hooks. This behavior for nullishsourceis temporary — in thefuture, nullishsourcewill 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.
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.mjsprints 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.coffeeornode --import ./coffeescript-sync-hooks.mjs ./main.coffeecausesmain.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.jsornode --import ./import-map-sync-hooks.js main.jsshould 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.SourceMapif a sourcemap is found,undefinedotherwise.
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 sourcegeneratedColumn<number> The column offset of start of therange in the generated sourceoriginalSource<string> The file name of the original source,as reported in the SourceMaporiginalLine<number> The line offset of the start of therange in the original sourceoriginalColumn<number> The column offset of start of therange in the original sourcename<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 providedfileName<string> The file name of the original source, asreported in the SourceMaplineNumber<number> The 1-indexed lineNumber of thecorresponding call site in the original sourcecolumnNumber<number> The 1-indexed columnNumber of thecorresponding call site in the original source