<Object>Provides general utility methods when interacting with instances of\nModule, the module variable often seen in CommonJS modules. Accessed\nvia import 'node:module' or require('node:module').
A list of the names of all modules provided by Node.js. Can be used to verify\nif a module is maintained by a third party or not.
\nmodule in this context isn't the same object that's provided\nby the module wrapper. To access it, require the Module module:
// module.mjs\n// In an ECMAScript module\nimport { builtinModules as builtin } from 'node:module';\n\n// module.cjs\n// In a CommonJS module\nconst builtin = require('node:module').builtinModules;\n"
}
],
"methods": [
{
"textRaw": "`module.createRequire(filename)`",
"name": "createRequire",
"type": "method",
"meta": {
"added": [
"v12.2.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`filename` {string|URL} Filename to be used to construct the require function. Must be a file URL object, file URL string, or absolute path string.",
"name": "filename",
"type": "string|URL",
"desc": "Filename to be used to construct the require function. Must be a file URL object, file URL string, or absolute path string."
}
],
"return": {
"textRaw": "Returns: {require} Require function",
"name": "return",
"type": "require",
"desc": "Require function"
}
}
],
"desc": "import { createRequire } from 'node:module';\nconst require = createRequire(import.meta.url);\n\n// sibling-module.js is a CommonJS module.\nconst siblingModule = require('./sibling-module');\n"
},
{
"textRaw": "`module.findPackageJSON(specifier[, base])`",
"name": "findPackageJSON",
"type": "method",
"meta": {
"added": [
"v23.2.0",
"v22.14.0"
],
"changes": []
},
"stability": 1.1,
"stabilityText": "Active Development",
"signatures": [
{
"params": [
{
"textRaw": "`specifier` {string|URL} The specifier for the module whose `package.json` to retrieve. When passing a _bare specifier_, the `package.json` at the root of the package is returned. When passing a _relative specifier_ or an _absolute specifier_, the closest parent `package.json` is returned.",
"name": "specifier",
"type": "string|URL",
"desc": "The specifier for the module whose `package.json` to retrieve. When passing a _bare specifier_, the `package.json` at the root of the package is returned. When passing a _relative specifier_ or an _absolute specifier_, the closest parent `package.json` is returned."
},
{
"textRaw": "`base` {string|URL} The absolute location (`file:` URL string or FS path) of the containing module. For CJS, use `__filename` (not `__dirname`!); for ESM, use `import.meta.url`. You do not need to pass it if `specifier` is an `absolute specifier`.",
"name": "base",
"type": "string|URL",
"desc": "The absolute location (`file:` URL string or FS path) of the containing module. For CJS, use `__filename` (not `__dirname`!); for ESM, use `import.meta.url`. You do not need to pass it if `specifier` is an `absolute specifier`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {string|undefined} A path if the `package.json` is found. When `specifier` is a package, the package's root `package.json`; when a relative or unresolved, the closest `package.json` to the `specifier`.",
"name": "return",
"type": "string|undefined",
"desc": "A path if the `package.json` is found. When `specifier` is a package, the package's root `package.json`; when a relative or unresolved, the closest `package.json` to the `specifier`."
}
}
],
"desc": "\n\nCaveat: Do not use this to try to determine module format. There are many things affecting\nthat determination; the
\ntypefield of package.json is the least definitive (ex file extension\nsupersedes it, and a loader hook supersedes that).
\n\nCaveat: This currently leverages only the built-in default resolver; if\n
\nresolvecustomization hooks are registered, they will not affect the resolution.\nThis may change in the future.
/path/to/project\n ├ packages/\n ├ bar/\n ├ bar.js\n └ package.json // name = '@foo/bar'\n └ qux/\n ├ node_modules/\n └ some-package/\n └ package.json // name = 'some-package'\n ├ qux.js\n └ package.json // name = '@foo/qux'\n ├ main.js\n └ package.json // name = '@foo'\n\n// /path/to/project/packages/bar/bar.js\nimport { findPackageJSON } from 'node:module';\n\nfindPackageJSON('..', import.meta.url);\n// '/path/to/project/package.json'\n// Same result when passing an absolute specifier instead:\nfindPackageJSON(new URL('../', import.meta.url));\nfindPackageJSON(import.meta.resolve('../'));\n\nfindPackageJSON('some-package', import.meta.url);\n// '/path/to/project/packages/bar/node_modules/some-package/package.json'\n// When passing an absolute specifier, you might get a different result if the\n// resolved module is inside a subfolder that has nested `package.json`.\nfindPackageJSON(import.meta.resolve('some-package'));\n// '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json'\n\nfindPackageJSON('@foo/qux', import.meta.url);\n// '/path/to/project/packages/qux/package.json'\n\n// /path/to/project/packages/bar/bar.js\nconst { findPackageJSON } = require('node:module');\nconst { pathToFileURL } = require('node:url');\nconst path = require('node:path');\n\nfindPackageJSON('..', __filename);\n// '/path/to/project/package.json'\n// Same result when passing an absolute specifier instead:\nfindPackageJSON(pathToFileURL(path.join(__dirname, '..')));\n\nfindPackageJSON('some-package', __filename);\n// '/path/to/project/packages/bar/node_modules/some-package/package.json'\n// When passing an absolute specifier, you might get a different result if the\n// resolved module is inside a subfolder that has nested `package.json`.\nfindPackageJSON(pathToFileURL(require.resolve('some-package')));\n// '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json'\n\nfindPackageJSON('@foo/qux', __filename);\n// '/path/to/project/packages/qux/package.json'\n"
},
{
"textRaw": "`module.isBuiltin(moduleName)`",
"name": "isBuiltin",
"type": "method",
"meta": {
"added": [
"v18.6.0",
"v16.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`moduleName` {string} name of the module",
"name": "moduleName",
"type": "string",
"desc": "name of the module"
}
],
"return": {
"textRaw": "Returns: {boolean} returns true if the module is builtin else returns false",
"name": "return",
"type": "boolean",
"desc": "returns true if the module is builtin else returns false"
}
}
],
"desc": "import { isBuiltin } from 'node:module';\nisBuiltin('node:fs'); // true\nisBuiltin('fs'); // true\nisBuiltin('wss'); // false\n"
},
{
"textRaw": "`module.register(specifier[, parentURL][, options])`",
"name": "register",
"type": "method",
"meta": {
"added": [
"v20.6.0",
"v18.19.0"
],
"changes": [
{
"version": [
"v23.6.1",
"v22.13.1",
"v20.18.2"
],
"pr-url": "https://github.com/nodejs-private/node-private/pull/629",
"description": "Using this feature with the permission model enabled requires passing `--allow-worker`."
},
{
"version": [
"v20.8.0",
"v18.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/49655",
"description": "Add support for WHATWG URL instances."
}
]
},
"stability": 1.1,
"stabilityText": "Active development",
"signatures": [
{
"params": [
{
"textRaw": "`specifier` {string|URL} Customization hooks to be registered; this should be the same string that would be passed to `import()`, except that if it is relative, it is resolved relative to `parentURL`.",
"name": "specifier",
"type": "string|URL",
"desc": "Customization hooks to be registered; this should be the same string that would be passed to `import()`, except that if it is relative, it is resolved relative to `parentURL`."
},
{
"textRaw": "`parentURL` {string|URL} If you want to resolve `specifier` relative to a base URL, such as `import.meta.url`, you can pass that URL here. **Default:** `'data:'`",
"name": "parentURL",
"type": "string|URL",
"default": "`'data:'`",
"desc": "If you want to resolve `specifier` relative to a base URL, such as `import.meta.url`, you can pass that URL here.",
"optional": true
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`parentURL` {string|URL} If you want to resolve `specifier` relative to a base URL, such as `import.meta.url`, you can pass that URL here. This property is ignored if the `parentURL` is supplied as the second argument. **Default:** `'data:'`",
"name": "parentURL",
"type": "string|URL",
"default": "`'data:'`",
"desc": "If you want to resolve `specifier` relative to a base URL, such as `import.meta.url`, you can pass that URL here. This property is ignored if the `parentURL` is supplied as the second argument."
},
{
"textRaw": "`data` {any} Any arbitrary, cloneable JavaScript value to pass into the `initialize` hook.",
"name": "data",
"type": "any",
"desc": "Any arbitrary, cloneable JavaScript value to pass into the `initialize` hook."
},
{
"textRaw": "`transferList` {Object[]} transferable objects to be passed into the `initialize` hook.",
"name": "transferList",
"type": "Object[]",
"desc": "transferable objects to be passed into the `initialize` hook."
}
],
"optional": true
}
]
}
],
"desc": "Register a module that exports hooks that customize Node.js module\nresolution and loading behavior. See Customization hooks.
\nThis feature requires --allow-worker if used with the Permission Model.
Register hooks that customize Node.js module resolution and loading behavior.\nSee Customization hooks.
" }, { "textRaw": "`module.stripTypeScriptTypes(code[, options])`", "name": "stripTypeScriptTypes", "type": "method", "meta": { "added": [ "v23.2.0", "v22.13.0" ], "changes": [] }, "stability": 1.2, "stabilityText": "Release candidate", "signatures": [ { "params": [ { "textRaw": "`code` {string} The code to strip type annotations from.", "name": "code", "type": "string", "desc": "The code to strip type annotations from." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`mode` {string} **Default:** `'strip'`. Possible values are:", "name": "mode", "type": "string", "default": "`'strip'`. Possible values are:", "options": [ { "textRaw": "`'strip'` Only strip type annotations without performing the transformation of TypeScript features.", "desc": "`'strip'` Only strip type annotations without performing the transformation of TypeScript features." }, { "textRaw": "`'transform'` Strip type annotations and transform TypeScript features to JavaScript.", "desc": "`'transform'` Strip type annotations and transform TypeScript features to JavaScript." } ] }, { "textRaw": "`sourceMap` {boolean} **Default:** `false`. Only when `mode` is `'transform'`, if `true`, a source map will be generated for the transformed code.", "name": "sourceMap", "type": "boolean", "default": "`false`. Only when `mode` is `'transform'`, if `true`, a source map will be generated for the transformed code" }, { "textRaw": "`sourceUrl` {string} Specifies the source url used in the source map.", "name": "sourceUrl", "type": "string", "desc": "Specifies the source url used in the source map." } ], "optional": true } ], "return": { "textRaw": "Returns: {string} The code with type annotations stripped.", "name": "return", "type": "string", "desc": "The code with type annotations stripped." } } ], "desc": "module.stripTypeScriptTypes() removes type annotations from TypeScript code. It\ncan be used to strip type annotations from TypeScript code before running it\nwith vm.runInContext() or vm.compileFunction().
By default, it will throw an error if the code contains TypeScript features\nthat require transformation such as Enums,\nsee type-stripping for more information.
When mode is 'transform', it also transforms TypeScript features to JavaScript,\nsee transform TypeScript features for more information.
When mode is 'strip', source maps are not generated, because locations are preserved.\nIf sourceMap 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,\ndue to changes in the TypeScript parser.
\nimport { stripTypeScriptTypes } from 'node:module';\nconst code = 'const a: number = 1;';\nconst strippedCode = stripTypeScriptTypes(code);\nconsole.log(strippedCode);\n// Prints: const a = 1;\n\nconst { stripTypeScriptTypes } = require('node:module');\nconst code = 'const a: number = 1;';\nconst strippedCode = stripTypeScriptTypes(code);\nconsole.log(strippedCode);\n// Prints: const a = 1;\n\nIf sourceUrl is provided, it will be used appended as a comment at the end of the output:
import { stripTypeScriptTypes } from 'node:module';\nconst code = 'const a: number = 1;';\nconst strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' });\nconsole.log(strippedCode);\n// Prints: const a = 1\\n\\n//# sourceURL=source.ts;\n\nconst { stripTypeScriptTypes } = require('node:module');\nconst code = 'const a: number = 1;';\nconst strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' });\nconsole.log(strippedCode);\n// Prints: const a = 1\\n\\n//# sourceURL=source.ts;\n\nWhen mode is 'transform', the code is transformed to JavaScript:
import { stripTypeScriptTypes } from 'node:module';\nconst code = `\n namespace MathUtil {\n export const add = (a: number, b: number) => a + b;\n }`;\nconst strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true });\nconsole.log(strippedCode);\n// Prints:\n// var MathUtil;\n// (function(MathUtil) {\n// MathUtil.add = (a, b)=>a + b;\n// })(MathUtil || (MathUtil = {}));\n// # sourceMappingURL=data:application/json;base64, ...\n\nconst { stripTypeScriptTypes } = require('node:module');\nconst code = `\n namespace MathUtil {\n export const add = (a: number, b: number) => a + b;\n }`;\nconst strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true });\nconsole.log(strippedCode);\n// Prints:\n// var MathUtil;\n// (function(MathUtil) {\n// MathUtil.add = (a, b)=>a + b;\n// })(MathUtil || (MathUtil = {}));\n// # sourceMappingURL=data:application/json;base64, ...\n"
},
{
"textRaw": "`module.syncBuiltinESMExports()`",
"name": "syncBuiltinESMExports",
"type": "method",
"meta": {
"added": [
"v12.12.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "The module.syncBuiltinESMExports() method updates all the live bindings for\nbuiltin ES Modules to match the properties of the CommonJS exports. It\ndoes not add or remove exported names from the ES Modules.
const fs = require('node:fs');\nconst assert = require('node:assert');\nconst { syncBuiltinESMExports } = require('node:module');\n\nfs.readFile = newAPI;\n\ndelete fs.readFileSync;\n\nfunction newAPI() {\n // ...\n}\n\nfs.newAPI = newAPI;\n\nsyncBuiltinESMExports();\n\nimport('node:fs').then((esmFS) => {\n // It syncs the existing readFile property with the new value\n assert.strictEqual(esmFS.readFile, newAPI);\n // readFileSync has been deleted from the required fs\n assert.strictEqual('readFileSync' in fs, false);\n // syncBuiltinESMExports() does not remove readFileSync from esmFS\n assert.strictEqual('readFileSync' in esmFS, true);\n // syncBuiltinESMExports() does not add names\n assert.strictEqual(esmFS.newAPI, undefined);\n});\n"
}
],
"displayName": "The `Module` object"
},
{
"textRaw": "Module compile cache",
"name": "module_compile_cache",
"type": "module",
"meta": {
"added": [
"v22.1.0"
],
"changes": [
{
"version": "v22.8.0",
"pr-url": "https://github.com/nodejs/node/pull/54501",
"description": "add initial JavaScript APIs for runtime access."
}
]
},
"desc": "The module compile cache can be enabled either using the module.enableCompileCache()\nmethod or the NODE_COMPILE_CACHE=dir environment variable. After it is enabled,\nwhenever Node.js compiles a CommonJS, a ECMAScript Module, or a TypeScript module, it will\nuse on-disk V8 code cache persisted in the specified directory to speed up the compilation.\nThis may slow down the first load of a module graph, but subsequent loads of the same module\ngraph 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 cache\ndirectory will be recreated the next time the same directory is used for for compile cache\nstorage. To avoid filling up the disk with stale cache, it is recommended to use a directory\nunder the os.tmpdir(). If the compile cache is enabled by a call to\nmodule.enableCompileCache() without specifying the directory, Node.js will use\nthe NODE_COMPILE_CACHE=dir environment variable if it's set, or defaults\nto path.join(os.tmpdir(), 'node-compile-cache') otherwise. To locate the compile cache\ndirectory used by a running Node.js instance, use module.getCompileCacheDir().
The enabled module compile cache can be disabled by the NODE_DISABLE_COMPILE_CACHE=1\nenvironment variable. This can be useful when the compile cache leads to unexpected or\nundesired behaviors (e.g. less precise test coverage).
At the moment, when the compile cache is enabled and a module is loaded afresh, the\ncode cache is generated from the compiled code immediately, but will only be written\nto disk when the Node.js instance is about to exit. This is subject to change. The\nmodule.flushCompileCache() method can be used to ensure the accumulated code cache\nis flushed to disk in case the application wants to spawn other Node.js instances\nand let them share the cache long before the parent exits.
The compile cache layout on disk is an implementation detail and should not be\nrelied upon. The compile cache generated is typically only reusable in the same\nversion of Node.js, and should be not assumed to be compatible across different\nversions of Node.js.
", "modules": [ { "textRaw": "Portability of the compile cache", "name": "portability_of_the_compile_cache", "type": "module", "desc": "By default, caches are invalidated when the absolute paths of the modules being\ncached are changed. To keep the cache working after moving the\nproject directory, enable portable compile cache. This allows previously compiled\nmodules to be reused across different directory locations as long as the layout relative\nto the cache directory remains the same. This would be done on a best-effort basis. If\nNode.js cannot compute the location of a module relative to the cache directory, the module\nwill not be cached.
\nThere are two ways to enable the portable mode:
\nUsing the portable option in module.enableCompileCache():
// Non-portable cache (default): cache breaks if project is moved\nmodule.enableCompileCache({ directory: '/path/to/cache/storage/dir' });\n\n// Portable cache: cache works after the project is moved\nmodule.enableCompileCache({ directory: '/path/to/cache/storage/dir', portable: true });\n\nSetting the environment variable: NODE_COMPILE_CACHE_PORTABLE=1
Currently when using the compile cache with V8 JavaScript code coverage, the\ncoverage being collected by V8 may be less precise in functions that are\ndeserialized from the code cache. It's recommended to turn this off when\nrunning tests to generate precise coverage.
\nCompilation cache generated by one version of Node.js can not be reused by a different\nversion of Node.js. Cache generated by different versions of Node.js will be stored\nseparately if the same base directory is used to persist the cache, so they can co-exist.
", "displayName": "Limitations of the compile cache" } ], "properties": [ { "textRaw": "`module.constants.compileCacheStatus`", "name": "compileCacheStatus", "type": "property", "meta": { "added": [ "v22.8.0" ], "changes": [ { "version": "v25.4.0", "pr-url": "https://github.com/nodejs/node/pull/60971", "description": "This feature is no longer experimental." } ] }, "desc": "The following constants are returned as the status field in the object returned by\nmodule.enableCompileCache() to indicate the result of the attempt to enable the\nmodule compile cache.
| Constant | Description |
|---|---|
ENABLED | \n Node.js has enabled the compile cache successfully. The directory used to store the\n compile cache will be returned in the directory field in the\n returned object.\n |
ALREADY_ENABLED | \n The compile cache has already been enabled before, either by a previous call to\n module.enableCompileCache(), or by the NODE_COMPILE_CACHE=dir\n environment variable. The directory used to store the\n compile cache will be returned in the directory field in the\n returned object.\n |
FAILED | \n Node.js fails to enable the compile cache. This can be caused by the lack of\n permission to use the specified directory, or various kinds of file system errors.\n The detail of the failure will be returned in the message field in the\n returned object.\n |
DISABLED | \n Node.js cannot enable the compile cache because the environment variable\n NODE_DISABLE_COMPILE_CACHE=1 has been set.\n |
Enable module compile cache in the current Node.js instance.
\nFor general use cases, it's recommended to call module.enableCompileCache() without\nspecifying the options.directory, so that the directory can be overridden by the\nNODE_COMPILE_CACHE environment variable when necessary.
Since compile cache is supposed to be a optimization that is not mission critical, this\nmethod is designed to not throw any exception when the compile cache cannot be enabled.\nInstead, it will return an object containing an error message in the message field to\naid debugging. If compile cache is enabled successfully, the directory field in the\nreturned object contains the path to the directory where the compile cache is stored. The\nstatus field in the returned object would be one of the module.constants.compileCacheStatus\nvalues to indicate the result of the attempt to enable the module compile cache.
This method only affects the current Node.js instance. To enable it in child worker threads,\neither call this method in child worker threads too, or set the\nprocess.env.NODE_COMPILE_CACHE value to compile cache directory so the behavior can\nbe inherited into the child workers. The directory can be obtained either from the\ndirectory field returned by this method, or with module.getCompileCacheDir().
Flush the module compile cache accumulated from modules already loaded\nin the current Node.js instance to disk. This returns after all the flushing\nfile system operations come to an end, no matter they succeed or not. If there\nare any errors, this will fail silently, since compile cache misses should not\ninterfere with the actual operation of the application.
" }, { "textRaw": "`module.getCompileCacheDir()`", "name": "getCompileCacheDir", "type": "method", "meta": { "added": [ "v22.8.0" ], "changes": [ { "version": "v25.4.0", "pr-url": "https://github.com/nodejs/node/pull/60971", "description": "This feature is no longer experimental." } ] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {string|undefined} Path to the module compile cache directory if it is enabled, or `undefined` otherwise.", "name": "return", "type": "string|undefined", "desc": "Path to the module compile cache directory if it is enabled, or `undefined` otherwise." } } ], "desc": "" } ], "displayName": "Module compile cache" }, { "textRaw": "Source Map Support", "name": "source_map_support", "type": "module", "meta": { "added": [ "v13.7.0", "v12.17.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "
Node.js supports TC39 ECMA-426 Source Map format (it was called Source map\nrevision 3 format).
\nThe APIs in this section are helpers for interacting with the source map\ncache. This cache is populated when source map parsing is enabled and\nsource map include directives are found in a modules' footer.
\nTo enable source map parsing, Node.js must be run with the flag\n--enable-source-maps, or with code coverage enabled by setting\nNODE_V8_COVERAGE=dir, or be enabled programmatically via\nmodule.setSourceMapsSupport().
// module.mjs\n// In an ECMAScript module\nimport { findSourceMap, SourceMap } from 'node:module';\n\n// module.cjs\n// In a CommonJS module\nconst { findSourceMap, SourceMap } = require('node:module');\n",
"methods": [
{
"textRaw": "`module.getSourceMapsSupport()`",
"name": "getSourceMapsSupport",
"type": "method",
"meta": {
"added": [
"v23.7.0",
"v22.14.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {Object}",
"name": "return",
"type": "Object",
"options": [
{
"textRaw": "`enabled` {boolean} If the source maps support is enabled",
"name": "enabled",
"type": "boolean",
"desc": "If the source maps support is enabled"
},
{
"textRaw": "`nodeModules` {boolean} If the support is enabled for files in `node_modules`.",
"name": "nodeModules",
"type": "boolean",
"desc": "If the support is enabled for files in `node_modules`."
},
{
"textRaw": "`generatedCode` {boolean} If the support is enabled for generated code from `eval` or `new Function`.",
"name": "generatedCode",
"type": "boolean",
"desc": "If the support is enabled for generated code from `eval` or `new Function`."
}
]
}
}
],
"desc": "This method returns whether the Source Map v3 support for stack\ntraces is enabled.
\n" }, { "textRaw": "`module.findSourceMap(path)`", "name": "findSourceMap", "type": "method", "meta": { "added": [ "v13.7.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`path` {string}", "name": "path", "type": "string" } ], "return": { "textRaw": "Returns: {module.SourceMap|undefined} Returns `module.SourceMap` if a source map is found, `undefined` otherwise.", "name": "return", "type": "module.SourceMap|undefined", "desc": "Returns `module.SourceMap` if a source map is found, `undefined` otherwise." } } ], "desc": "path is the resolved path for the file for which a corresponding source map\nshould be fetched.
This function enables or disables the Source Map v3 support for\nstack traces.
\nIt provides same features as launching Node.js process with commandline options\n--enable-source-maps, with additional options to alter the support for files\nin node_modules or generated codes.
Only source maps in JavaScript files that are loaded after source maps has been\nenabled will be parsed and loaded. Preferably, use the commandline options\n--enable-source-maps to avoid losing track of source maps of modules loaded\nbefore this API call.
Creates a new sourceMap instance.
payload is an object with keys matching the Source 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 the\ngenerated code.
Getter for the payload used to construct the SourceMap instance.
Given a line offset and column offset in the generated source\nfile, returns an object representing the SourceMap range in the\noriginal file if found, or an empty object if not.
\nThe object returned contains the following keys:
\ngeneratedLine <number> The line offset of the start of the\nrange in the generated sourcegeneratedColumn <number> The column offset of start of the\nrange in the generated sourceoriginalSource <string> The file name of the original source,\nas reported in the SourceMaporiginalLine <number> The line offset of the start of the\nrange in the original sourceoriginalColumn <number> The column offset of start of the\nrange in the original sourcename <string>The returned value represents the raw range as it appears in the\nSourceMap, based on zero-indexed offsets, not 1-indexed line and\ncolumn numbers as they appear in Error messages and CallSite\nobjects.
\nTo get the corresponding 1-indexed line and column numbers from a\nlineNumber and columnNumber as they are reported by Error stacks\nand CallSite objects, use sourceMap.findOrigin(lineNumber, columnNumber)
Given a 1-indexed lineNumber and columnNumber from a call site in\nthe generated source, find the corresponding call site location\nin the original source.
If the lineNumber and columnNumber provided are not found in any\nsource map, then an empty object is returned. Otherwise, the\nreturned object contains the following keys:
name <string> | <undefined> The name of the range in the\nsource map, if one was providedfileName <string> The file name of the original source, as\nreported in the SourceMaplineNumber <number> The 1-indexed lineNumber of the\ncorresponding call site in the original sourcecolumnNumber <number> The 1-indexed columnNumber of the\ncorresponding call site in the original sourceNode.js currently supports two types of module customization hooks:
\nmodule.registerHooks(options): takes synchronous hook\nfunctions that are run directly on the thread where the modules are loaded.module.register(specifier[, parentURL][, options]): takes specifier to a\nmodule that exports asynchronous hook functions. The functions are run on a\nseparate loader thread.The asynchronous hooks incur extra overhead from inter-thread communication,\nand have several caveats especially\nwhen customizing CommonJS modules in the module graph.\nIn most cases, it's recommended to use synchronous hooks via module.registerHooks()\nfor simplicity.
", "modules": [ { "textRaw": "Registration of synchronous customization hooks", "name": "registration_of_synchronous_customization_hooks", "type": "module", "desc": "
To register synchronous customization hooks, use module.registerHooks(), which\ntakes synchronous hook functions directly in-line.
// register-hooks.js\nimport { registerHooks } from 'node:module';\nregisterHooks({\n resolve(specifier, context, nextResolve) { /* implementation */ },\n load(url, context, nextLoad) { /* implementation */ },\n});\n\n// register-hooks.js\nconst { registerHooks } = require('node:module');\nregisterHooks({\n resolve(specifier, context, nextResolve) { /* implementation */ },\n load(url, context, nextLoad) { /* implementation */ },\n});\n",
"modules": [
{
"textRaw": "Registering hooks before application code runs with flags",
"name": "registering_hooks_before_application_code_runs_with_flags",
"type": "module",
"desc": "The hooks can be registered before the application code is run by using the\n--import or --require flag:
node --import ./register-hooks.js ./my-app.js\nnode --require ./register-hooks.js ./my-app.js\n\nThe specifier passed to --import or --require can also come from a package:
node --import some-package/register ./my-app.js\nnode --require some-package/register ./my-app.js\n\nWhere some-package has an \"exports\" field defining the /register\nexport to map to a file that calls registerHooks(), like the\nregister-hooks.js examples above.
Using --import or --require ensures that the hooks are registered before any\napplication code is loaded, including the entry point of the application and for\nany worker threads by default as well.
Alternatively, registerHooks() can be called from the entry point.
If the entry point needs to load other modules and the loading process needs to be\ncustomized, load them using either require() or dynamic import() after the hooks\nare registered. Do not use static import statements to load modules that need to be\ncustomized in the same module that registers the hooks, because static import statements\nare evaluated before any code in the importer module is run, including the call to\nregisterHooks(), regardless of where the static import statements appear in the importer\nmodule.
import { registerHooks } from 'node:module';\n\nregisterHooks({ /* implementation of synchronous hooks */ });\n\n// If loaded using static import, the hooks would not be applied when loading\n// my-app.mjs, because statically imported modules are all executed before its\n// importer regardless of where the static import appears.\n// import './my-app.mjs';\n\n// my-app.mjs must be loaded dynamically to ensure the hooks are applied.\nawait import('./my-app.mjs');\n\nconst { registerHooks } = require('node:module');\n\nregisterHooks({ /* implementation of synchronous hooks */ });\n\nimport('./my-app.mjs');\n// Or, if my-app.mjs does not have top-level await or it's a CommonJS module,\n// require() can also be used:\n// require('./my-app.mjs');\n",
"displayName": "Registering hooks before application code runs programmatically"
},
{
"textRaw": "Registering hooks before application code runs with a `data:` URL",
"name": "registering_hooks_before_application_code_runs_with_a_`data:`_url",
"type": "module",
"desc": "Alternatively, inline JavaScript code can be embedded in data: URLs to register\nthe hooks before the application code runs. For example,
node --import 'data:text/javascript,import {registerHooks} from \"node:module\"; registerHooks(/* hooks code */);' ./my-app.js\n",
"displayName": "Registering hooks before application code runs with a `data:` URL"
}
],
"displayName": "Registration of synchronous customization hooks"
},
{
"textRaw": "Convention of hooks and chaining",
"name": "convention_of_hooks_and_chaining",
"type": "module",
"desc": "Hooks are part of a chain, even if that chain consists of only one\ncustom (user-provided) hook and the default hook, which is always present.
\nHook functions nest: each one must always return a plain object, and chaining happens\nas a result of each function calling next<hookName>(), which is a reference to\nthe subsequent loader's hook (in LIFO order).
It's possible to call registerHooks() more than once:
// entrypoint.mjs\nimport { registerHooks } from 'node:module';\n\nconst hook1 = { /* implementation of hooks */ };\nconst hook2 = { /* implementation of hooks */ };\n// hook2 runs before hook1.\nregisterHooks(hook1);\nregisterHooks(hook2);\n\n// entrypoint.cjs\nconst { registerHooks } = require('node:module');\n\nconst hook1 = { /* implementation of hooks */ };\nconst hook2 = { /* implementation of hooks */ };\n// hook2 runs before hook1.\nregisterHooks(hook1);\nregisterHooks(hook2);\n\nIn this example, the registered hooks will form chains. These chains run\nlast-in, first-out (LIFO). If both hook1 and hook2 define a resolve\nhook, they will be called like so (note the right-to-left,\nstarting with hook2.resolve, then hook1.resolve, then the Node.js default):
Node.js default resolve ← hook1.resolve ← hook2.resolve
The same applies to all the other hooks.
\nA hook that returns a value lacking a required property triggers an exception. A\nhook that returns without calling next<hookName>() and without returning\nshortCircuit: true also triggers an exception. These errors are to help\nprevent unintentional breaks in the chain. Return shortCircuit: true from a\nhook to signal that the chain is intentionally ending at your hook.
If a hook should be applied when loading other hook modules, the other hook\nmodules should be loaded after the hook is registered.
", "displayName": "Convention of hooks and chaining" }, { "textRaw": "Hook functions accepted by `module.registerHooks()`", "name": "hook_functions_accepted_by_`module.registerhooks()`", "type": "module", "meta": { "added": [ "v23.5.0", "v22.15.0" ], "changes": [] }, "desc": "The module.registerHooks() method accepts the following synchronous hook functions.
function resolve(specifier, context, nextResolve) {\n // Take an `import` or `require` specifier and resolve it to a URL.\n}\n\nfunction load(url, context, nextLoad) {\n // Take a resolved URL and return the source code to be evaluated.\n}\n\nSynchronous hooks are run in the same thread and the same realm where the modules\nare loaded, the code in the hook function can pass values to the modules being referenced\ndirectly via global variables or other shared states.
\nUnlike the asynchronous hooks, the synchronous hooks are not inherited into child worker\nthreads by default, though if the hooks are registered using a file preloaded by\n--import or --require, child worker threads can inherit the preloaded scripts\nvia process.execArgv inheritance. See the documentation of Worker for details.
specifier <string>context <Object>\nconditions <string[]> Export conditions of the relevant package.jsonimportAttributes <Object> An object whose key-value pairs represent the\nattributes for the module to importparentURL <string> | <undefined> The module importing this one, or undefined\nif this is the Node.js entry pointnextResolve <Function> The subsequent resolve hook in the chain, or the\nNode.js default resolve hook after the last user-supplied resolve hook\nspecifier <string>context <Object> | <undefined> When omitted, the defaults are provided. When provided, defaults\nare merged in with preference to the provided properties.<Object>\nformat <string> | <null> | <undefined> A hint to the load hook (it might be ignored). It can be a\nmodule format (such as 'commonjs' or 'module') or an arbitrary value like 'css' or\n'yaml'.importAttributes <Object> | <undefined> The import attributes to use when\ncaching the module (optional; if excluded the input will be used)shortCircuit <undefined> | <boolean> A signal that this hook intends to\nterminate the chain of resolve hooks. Default: falseurl <string> The absolute URL to which this input resolvesThe resolve hook chain is responsible for telling Node.js where to find and\nhow to cache a given import statement or expression, or require call. It can\noptionally return a format (such as 'module') as a hint to the load hook. If\na format is specified, the load hook is ultimately responsible for providing\nthe final format value (and it is free to ignore the hint provided by\nresolve); if resolve provides a format, a custom load hook is required\neven if only to pass the value to the Node.js default load hook.
Import type attributes are part of the cache key for saving loaded modules into\nthe internal module cache. The resolve hook is responsible for returning an\nimportAttributes object if the module should be cached with different\nattributes than were present in the source code.
The conditions property in context is an array of conditions that will be used\nto match package exports conditions for this resolution\nrequest. They can be used for looking up conditional mappings elsewhere or to\nmodify the list when calling the default resolution logic.
The current package exports conditions are always in\nthe context.conditions array passed into the hook. To guarantee default\nNode.js module specifier resolution behavior when calling defaultResolve, the\ncontext.conditions array passed to it must include all elements of the\ncontext.conditions array originally passed into the resolve hook.
import { registerHooks } from 'node:module';\n\nfunction resolve(specifier, context, nextResolve) {\n // When calling `defaultResolve`, the arguments can be modified. For example,\n // to change the specifier or to add applicable export conditions.\n if (specifier.includes('foo')) {\n specifier = specifier.replace('foo', 'bar');\n return nextResolve(specifier, {\n ...context,\n conditions: [...context.conditions, 'another-condition'],\n });\n }\n\n // The hook can also skip default resolution and provide a custom URL.\n if (specifier === 'special-module') {\n return {\n url: 'file:///path/to/special-module.mjs',\n format: 'module',\n shortCircuit: true, // This is mandatory if nextResolve() is not called.\n };\n }\n\n // If no customization is needed, defer to the next hook in the chain which would be the\n // Node.js default resolve if this is the last user-specified loader.\n return nextResolve(specifier);\n}\n\nregisterHooks({ resolve });\n",
"displayName": "Synchronous `resolve(specifier, context, nextResolve)`"
},
{
"textRaw": "Synchronous `load(url, context, nextLoad)`",
"name": "synchronous_`load(url,_context,_nextload)`",
"type": "module",
"meta": {
"changes": [
{
"version": [
"v23.5.0",
"v22.15.0"
],
"pr-url": "https://github.com/nodejs/node/pull/55698",
"description": "Add support for synchronous and in-thread version."
}
]
},
"desc": "url <string> The URL returned by the resolve chaincontext <Object>\nconditions <string[]> Export conditions of the relevant package.jsonformat <string> | <null> | <undefined> The format optionally supplied by the resolve hook chain. This can be any string value as an input; input values do not need to\nconform to the list of acceptable return values described below.importAttributes <Object>nextLoad <Function> The subsequent load hook in the chain, or the\nNode.js default load hook after the last user-supplied load hook\nurl <string>context <Object> | <undefined> When omitted, defaults are provided. When provided, defaults are\nmerged in with preference to the provided properties. In the default nextLoad, if\nthe module pointed to by url does not have explicit module type information,\ncontext.format is mandatory.\n\n<Object>\nformat <string> One of the acceptable module formats listed below.shortCircuit <undefined> | <boolean> A signal that this hook intends to\nterminate the chain of load hooks. Default: falsesource <string> | <ArrayBuffer> | <TypedArray> The source for Node.js to evaluateThe load hook provides a way to define a custom method for retrieving the\nsource code of a resolved URL. This would allow a loader to potentially avoid\nreading files from disk. It could also be used to map an unrecognized format to\na supported one, for example yaml to module.
import { registerHooks } from 'node:module';\nimport { Buffer } from 'node:buffer';\n\nfunction load(url, context, nextLoad) {\n // The hook can skip default loading and provide a custom source code.\n if (url === 'special-module') {\n return {\n source: 'export const special = 42;',\n format: 'module',\n shortCircuit: true, // This is mandatory if nextLoad() is not called.\n };\n }\n\n // It's possible to modify the source code loaded by the next - possibly default - step,\n // for example, replacing 'foo' with 'bar' in the source code of the module.\n const result = nextLoad(url, context);\n const source = typeof result.source === 'string' ?\n result.source : Buffer.from(result.source).toString('utf8');\n return {\n source: source.replace(/foo/g, 'bar'),\n ...result,\n };\n}\n\nregisterHooks({ resolve });\n\nIn a more advanced scenario, this can also be used to transform an unsupported\nsource to a supported one (see Examples below).
", "modules": [ { "textRaw": "Accepted final formats returned by `load`", "name": "accepted_final_formats_returned_by_`load`", "type": "module", "desc": "The final value of format must be one of the following:
format | Description | Acceptable types for source returned by load |
|---|---|---|
'addon' | Load a Node.js addon | <null> |
'builtin' | Load a Node.js builtin module | <null> |
'commonjs-typescript' | Load a Node.js CommonJS module with TypeScript syntax | <string> | <ArrayBuffer> | <TypedArray> | <null> | <undefined> |
'commonjs' | Load a Node.js CommonJS module | <string> | <ArrayBuffer> | <TypedArray> | <null> | <undefined> |
'json' | Load a JSON file | <string> | <ArrayBuffer> | <TypedArray> |
'module-typescript' | Load an ES module with TypeScript syntax | <string> | <ArrayBuffer> | <TypedArray> |
'module' | Load an ES module | <string> | <ArrayBuffer> | <TypedArray> |
'wasm' | Load a WebAssembly module | <ArrayBuffer> | <TypedArray> |
The value of source is ignored for format 'builtin' because currently it is\nnot possible to replace the value of a Node.js builtin (core) module.
\n\nThese types all correspond to classes defined in ECMAScript.
\n
<ArrayBuffer> object is a <SharedArrayBuffer>.<TypedArray> object is a <Uint8Array>.If the source value of a text-based format (i.e., 'json', 'module')\nis not a string, it is converted to a string using util.TextDecoder.
The asynchronous customization hooks have many caveats and it is uncertain if their\nissues can be resolved. Users are encouraged to use the synchronous customization hooks\nvia module.registerHooks() instead to avoid these caveats.
require() calls in the module graph.\nrequire functions created using module.createRequire() are not\naffected.load hook does not override the source for CommonJS modules\nthat go through it, the child modules loaded by those CommonJS modules via built-in\nrequire() would not be affected by the asynchronous hooks either.resolve hook and\nasynchronous load hook for details.require() calls inside CommonJS modules are customized by asynchronous hooks,\nNode.js may need to load the source code of the CommonJS module multiple times to maintain\ncompatibility with existing CommonJS monkey-patching. If the module code changes between\nloads, this may lead to unexpected behaviors.\nrequire() calls in that CommonJS module.Asynchronous customization hooks are registered using module.register() which takes\na path or URL to another module that exports the asynchronous hook functions.
Similar to registerHooks(), register() can be called in a module preloaded by --import or\n--require, or called directly within the entry point.
// Use module.register() to register asynchronous hooks in a dedicated thread.\nimport { register } from 'node:module';\nregister('./hooks.mjs', import.meta.url);\n\n// If my-app.mjs is loaded statically here as `import './my-app.mjs'`, since ESM\n// dependencies are evaluated before the module that imports them,\n// it's loaded _before_ the hooks are registered above and won't be affected.\n// To ensure the hooks are applied, dynamic import() must be used to load ESM\n// after the hooks are registered.\nimport('./my-app.mjs');\n\nconst { register } = require('node:module');\nconst { pathToFileURL } = require('node:url');\n// Use module.register() to register asynchronous hooks in a dedicated thread.\nregister('./hooks.mjs', pathToFileURL(__filename));\n\nimport('./my-app.mjs');\n\nIn hooks.mjs:
// hooks.mjs\nexport async function resolve(specifier, context, nextResolve) {\n /* implementation */\n}\nexport async function load(url, context, nextLoad) {\n /* implementation */\n}\n\nUnlike synchronous hooks, the asynchronous hooks would not run for these modules loaded in the file\nthat calls register():
// register-hooks.js\nimport { register, createRequire } from 'node:module';\nregister('./hooks.mjs', import.meta.url);\n\n// Asynchronous hooks does not affect modules loaded via custom require()\n// functions created by module.createRequire().\nconst userRequire = createRequire(__filename);\nuserRequire('./my-app-2.cjs'); // Hooks won't affect this\n\n// register-hooks.js\nconst { register, createRequire } = require('node:module');\nconst { pathToFileURL } = require('node:url');\nregister('./hooks.mjs', pathToFileURL(__filename));\n\n// Asynchronous hooks does not affect modules loaded via built-in require()\n// in the module calling `register()`\nrequire('./my-app-2.cjs'); // Hooks won't affect this\n// .. or custom require() functions created by module.createRequire().\nconst userRequire = createRequire(__filename);\nuserRequire('./my-app-3.cjs'); // Hooks won't affect this\n\nAsynchronous hooks can also be registered using a data: URL with the --import flag:
node --import 'data:text/javascript,import { register } from \"node:module\"; import { pathToFileURL } from \"node:url\"; register(\"my-instrumentation\", pathToFileURL(\"./\"));' ./my-app.js\n",
"displayName": "Registration of asynchronous customization hooks"
},
{
"textRaw": "Chaining of asynchronous customization hooks",
"name": "chaining_of_asynchronous_customization_hooks",
"type": "module",
"desc": "Chaining of register() work similarly to registerHooks(). If synchronous and asynchronous\nhooks are mixed, the synchronous hooks are always run first before the asynchronous\nhooks start running, that is, in the last synchronous hook being run, its next\nhook includes invocation of the asynchronous hooks.
// entrypoint.mjs\nimport { register } from 'node:module';\n\nregister('./foo.mjs', import.meta.url);\nregister('./bar.mjs', import.meta.url);\nawait import('./my-app.mjs');\n\n// entrypoint.cjs\nconst { register } = require('node:module');\nconst { pathToFileURL } = require('node:url');\n\nconst parentURL = pathToFileURL(__filename);\nregister('./foo.mjs', parentURL);\nregister('./bar.mjs', parentURL);\nimport('./my-app.mjs');\n\nIf foo.mjs and bar.mjs define a resolve hook, they will be called like so\n(note the right-to-left, starting with ./bar.mjs, then ./foo.mjs, then the Node.js default):
Node.js default ← ./foo.mjs ← ./bar.mjs
When using the asynchronous hooks, the registered hooks also affect subsequent\nregister calls, which takes care of loading hook modules. In the example above,\nbar.mjs will be resolved and loaded via the hooks registered by foo.mjs\n(because foo's hooks will have already been added to the chain). This allows\nfor things like writing hooks in non-JavaScript languages, so long as\nearlier registered hooks transpile into JavaScript.
The register() method cannot be called from the thread running the hook module that\nexports the asynchronous hooks or its dependencies.
Asynchronous hooks run on a dedicated thread, separate from the main\nthread that runs application code. This means mutating global variables won't\naffect the other thread(s), and message channels must be used to communicate\nbetween the threads.
\nThe register method can be used to pass data to an initialize hook. The\ndata passed to the hook may include transferable objects like ports.
import { register } from 'node:module';\nimport { MessageChannel } from 'node:worker_threads';\n\n// This example demonstrates how a message channel can be used to\n// communicate with the hooks, by sending `port2` to the hooks.\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (msg) => {\n console.log(msg);\n});\nport1.unref();\n\nregister('./my-hooks.mjs', {\n parentURL: import.meta.url,\n data: { number: 1, port: port2 },\n transferList: [port2],\n});\n\nconst { register } = require('node:module');\nconst { pathToFileURL } = require('node:url');\nconst { MessageChannel } = require('node:worker_threads');\n\n// This example showcases how a message channel can be used to\n// communicate with the hooks, by sending `port2` to the hooks.\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (msg) => {\n console.log(msg);\n});\nport1.unref();\n\nregister('./my-hooks.mjs', {\n parentURL: pathToFileURL(__filename),\n data: { number: 1, port: port2 },\n transferList: [port2],\n});\n",
"displayName": "Communication with asynchronous module customization hooks"
},
{
"textRaw": "Asynchronous hooks accepted by `module.register()`",
"name": "asynchronous_hooks_accepted_by_`module.register()`",
"type": "module",
"meta": {
"added": [
"v8.8.0"
],
"changes": [
{
"version": [
"v20.6.0",
"v18.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/48842",
"description": "Added `initialize` hook to replace `globalPreload`."
},
{
"version": [
"v18.6.0",
"v16.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/42623",
"description": "Add support for chaining loaders."
},
{
"version": "v16.12.0",
"pr-url": "https://github.com/nodejs/node/pull/37468",
"description": "Removed `getFormat`, `getSource`, `transformSource`, and `globalPreload`; added `load` hook and `getGlobalPreload` hook."
}
]
},
"desc": "The register method can be used to register a module that exports a set of\nhooks. The hooks are functions that are called by Node.js to customize the\nmodule resolution and loading process. The exported functions must have specific\nnames and signatures, and they must be exported as named exports.
export async function initialize({ number, port }) {\n // Receives data from `register`.\n}\n\nexport async function resolve(specifier, context, nextResolve) {\n // Take an `import` or `require` specifier and resolve it to a URL.\n}\n\nexport async function load(url, context, nextLoad) {\n // Take a resolved URL and return the source code to be evaluated.\n}\n\nAsynchronous hooks are run in a separate thread, isolated from the main thread where\napplication code runs. That means it is a different realm. The hooks thread\nmay be terminated by the main thread at any time, so do not depend on\nasynchronous operations (like console.log) to complete. They are inherited into\nchild workers by default.
specifier <string>context <Object>\nconditions <string[]> Export conditions of the relevant package.jsonimportAttributes <Object> An object whose key-value pairs represent the\nattributes for the module to importparentURL <string> | <undefined> The module importing this one, or undefined\nif this is the Node.js entry pointnextResolve <Function> The subsequent resolve hook in the chain, or the\nNode.js default resolve hook after the last user-supplied resolve hook\nspecifier <string>context <Object> | <undefined> When omitted, the defaults are provided. When provided, defaults\nare merged in with preference to the provided properties.<Object> | <Promise> The asynchronous version takes either an object containing the\nfollowing properties, or a Promise that will resolve to such an object.\nformat <string> | <null> | <undefined> A hint to the load hook (it might be ignored). It can be a\nmodule format (such as 'commonjs' or 'module') or an arbitrary value like 'css' or\n'yaml'.importAttributes <Object> | <undefined> The import attributes to use when\ncaching the module (optional; if excluded the input will be used)shortCircuit <undefined> | <boolean> A signal that this hook intends to\nterminate the chain of resolve hooks. Default: falseurl <string> The absolute URL to which this input resolvesThe asynchronous version works similarly to the synchronous version, only that the\nnextResolve function returns a Promise, and the resolve hook itself can return a Promise.
\n\nWarning In the case of the asynchronous version, despite support for returning\npromises and async functions, calls to
\nresolvemay still block the main thread which\ncan impact performance.
\n\nWarning The
\nresolvehook invoked forrequire()calls inside CommonJS modules\ncustomized by asynchronous hooks does not receive the original specifier passed to\nrequire(). Instead, it receives a URL already fully resolved using the default\nCommonJS resolution.
\n\nWarning In the CommonJS modules that are customized by the asynchronous customization hooks,\n
\nrequire.resolve()andrequire()will use\"import\"export condition instead of\n\"require\", which may cause unexpected behaviors when loading dual packages.
export async function resolve(specifier, context, nextResolve) {\n // When calling `defaultResolve`, the arguments can be modified. For example,\n // to change the specifier or add conditions.\n if (specifier.includes('foo')) {\n specifier = specifier.replace('foo', 'bar');\n return nextResolve(specifier, {\n ...context,\n conditions: [...context.conditions, 'another-condition'],\n });\n }\n\n // The hook can also skips default resolution and provide a custom URL.\n if (specifier === 'special-module') {\n return {\n url: 'file:///path/to/special-module.mjs',\n format: 'module',\n shortCircuit: true, // This is mandatory if not calling nextResolve().\n };\n }\n\n // If no customization is needed, defer to the next hook in the chain which would be the\n // Node.js default resolve if this is the last user-specified loader.\n return nextResolve(specifier);\n}\n",
"displayName": "Asynchronous `resolve(specifier, context, nextResolve)`"
},
{
"textRaw": "Asynchronous `load(url, context, nextLoad)`",
"name": "asynchronous_`load(url,_context,_nextload)`",
"type": "module",
"meta": {
"changes": [
{
"version": "v22.6.0",
"pr-url": "https://github.com/nodejs/node/pull/56350",
"description": "Add support for `source` with format `commonjs-typescript` and `module-typescript`."
},
{
"version": "v20.6.0",
"pr-url": "https://github.com/nodejs/node/pull/47999",
"description": "Add support for `source` with format `commonjs`."
},
{
"version": [
"v18.6.0",
"v16.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/42623",
"description": "Add support for chaining load hooks. Each hook must either call `nextLoad()` or include a `shortCircuit` property set to `true` in its return."
}
]
},
"desc": "url <string> The URL returned by the resolve chaincontext <Object>\nconditions <string[]> Export conditions of the relevant package.jsonformat <string> | <null> | <undefined> The format optionally supplied by the resolve hook chain. This can be any string value as an input; input values do not need to\nconform to the list of acceptable return values described below.importAttributes <Object>nextLoad <Function> The subsequent load hook in the chain, or the\nNode.js default load hook after the last user-supplied load hook\nurl <string>context <Object> | <undefined> When omitted, defaults are provided. When provided, defaults are\nmerged in with preference to the provided properties. In the default nextLoad, if\nthe module pointed to by url does not have explicit module type information,\ncontext.format is mandatory.\n\n<Promise> The asynchronous version takes either an object containing the\nfollowing properties, or a Promise that will resolve to such an object.\nformat <string>shortCircuit <undefined> | <boolean> A signal that this hook intends to\nterminate the chain of load hooks. Default: falsesource <string> | <ArrayBuffer> | <TypedArray> The source for Node.js to evaluate\n\nWarning: The asynchronous
\nloadhook and namespaced exports from CommonJS\nmodules are incompatible. Attempting to use them together will result in an empty\nobject from the import. This may be addressed in the future. This does not apply\nto the synchronousloadhook, in which case exports can be used as usual.
The asynchronous version works similarly to the synchronous version, though\nwhen using the asynchronous load hook, omitting vs providing a source for\n'commonjs' has very different effects:
source is provided, all require calls from this module will be\nprocessed by the ESM loader with registered resolve and load hooks; all\nrequire.resolve calls from this module will be processed by the ESM loader\nwith registered resolve hooks; only a subset of the CommonJS API will be\navailable (e.g. no require.extensions, no require.cache, no\nrequire.resolve.paths) and monkey-patching on the CommonJS module loader\nwill not apply.source is undefined or null, it will be handled by the CommonJS module\nloader and require/require.resolve calls will not go through the\nregistered hooks. This behavior for nullish source is temporary — in the\nfuture, nullish source will not be supported.These caveats do not apply to the synchronous load hook, in which case\nthe complete set of CommonJS APIs available to the customized CommonJS\nmodules, and require/require.resolve always go through the registered\nhooks.
The Node.js internal asynchronous load implementation, which is the value of next for the\nlast hook in the load chain, returns null for source when format is\n'commonjs' for backward compatibility. Here is an example hook that would\nopt-in to using the non-default behavior:
import { readFile } from 'node:fs/promises';\n\n// Asynchronous version accepted by module.register(). This fix is not needed\n// for the synchronous version accepted by module.registerHooks().\nexport async function load(url, context, nextLoad) {\n const result = await nextLoad(url, context);\n if (result.format === 'commonjs') {\n result.source ??= await readFile(new URL(result.responseURL ?? url));\n }\n return result;\n}\n\nThis doesn't apply to the synchronous load hook either, in which case the\nsource returned contains source code loaded by the next hook, regardless\nof module format.
The initialize hook is only accepted by register. registerHooks() does\nnot support nor need it since initialization done for synchronous hooks can be run\ndirectly before the call to registerHooks().
The initialize hook provides a way to define a custom function that runs in\nthe hooks thread when the hooks module is initialized. Initialization happens\nwhen the hooks module is registered via register.
This hook can receive data from a register invocation, including\nports and other transferable objects. The return value of initialize can be a\n<Promise>, in which case it will be awaited before the main application thread\nexecution resumes.
Module customization code:
\n// path-to-my-hooks.js\n\nexport async function initialize({ number, port }) {\n port.postMessage(`increment: ${number + 1}`);\n}\n\nCaller code:
\nimport assert from 'node:assert';\nimport { register } from 'node:module';\nimport { MessageChannel } from 'node:worker_threads';\n\n// This example showcases how a message channel can be used to communicate\n// between the main (application) thread and the hooks running on the hooks\n// thread, by sending `port2` to the `initialize` hook.\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (msg) => {\n assert.strictEqual(msg, 'increment: 2');\n});\nport1.unref();\n\nregister('./path-to-my-hooks.js', {\n parentURL: import.meta.url,\n data: { number: 1, port: port2 },\n transferList: [port2],\n});\n\nconst assert = require('node:assert');\nconst { register } = require('node:module');\nconst { pathToFileURL } = require('node:url');\nconst { MessageChannel } = require('node:worker_threads');\n\n// This example showcases how a message channel can be used to communicate\n// between the main (application) thread and the hooks running on the hooks\n// thread, by sending `port2` to the `initialize` hook.\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (msg) => {\n assert.strictEqual(msg, 'increment: 2');\n});\nport1.unref();\n\nregister('./path-to-my-hooks.js', {\n parentURL: pathToFileURL(__filename),\n data: { number: 1, port: port2 },\n transferList: [port2],\n});\n"
}
],
"displayName": "Asynchronous customization hooks"
},
{
"textRaw": "Examples",
"name": "examples",
"type": "misc",
"desc": "The various module customization hooks can be used together to accomplish\nwide-ranging customizations of the Node.js code loading and evaluation\nbehaviors.
", "modules": [ { "textRaw": "Import from HTTPS", "name": "import_from_https", "type": "module", "desc": "The hook below registers hooks to enable rudimentary support for such\nspecifiers. While this may seem like a significant improvement to Node.js core\nfunctionality, there are substantial downsides to actually using these hooks:\nperformance is much slower than loading files from disk, there is no caching,\nand there is no security.
\n// https-hooks.mjs\nimport { get } from 'node:https';\n\nexport function load(url, context, nextLoad) {\n // For JavaScript to be loaded over the network, we need to fetch and\n // return it.\n if (url.startsWith('https://')) {\n return new Promise((resolve, reject) => {\n get(url, (res) => {\n let data = '';\n res.setEncoding('utf8');\n res.on('data', (chunk) => data += chunk);\n res.on('end', () => resolve({\n // This example assumes all network-provided JavaScript is ES module\n // code.\n format: 'module',\n shortCircuit: true,\n source: data,\n }));\n }).on('error', (err) => reject(err));\n });\n }\n\n // Let Node.js handle all other URLs.\n return nextLoad(url);\n}\n\n// main.mjs\nimport { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';\n\nconsole.log(VERSION);\n\nWith the preceding hooks module, running\nnode --import 'data:text/javascript,import { register } from \"node:module\"; import { pathToFileURL } from \"node:url\"; register(pathToFileURL(\"./https-hooks.mjs\"));' ./main.mjs\nprints the current version of CoffeeScript per the module at the URL in\nmain.mjs.
Sources that are in formats Node.js doesn't understand can be converted into\nJavaScript using the load hook.
This is less performant than transpiling source files before running Node.js;\ntranspiler hooks should only be used for development and testing purposes.
", "modules": [ { "textRaw": "Asynchronous version", "name": "asynchronous_version", "type": "module", "desc": "// coffeescript-hooks.mjs\nimport { readFile } from 'node:fs/promises';\nimport { findPackageJSON } from 'node:module';\nimport coffeescript from 'coffeescript';\n\nconst extensionsRegex = /\\.(coffee|litcoffee|coffee\\.md)$/;\n\nexport async function load(url, context, nextLoad) {\n if (extensionsRegex.test(url)) {\n // CoffeeScript files can be either CommonJS or ES modules. Use a custom format\n // to tell Node.js not to detect its module type.\n const { source: rawSource } = await nextLoad(url, { ...context, format: 'coffee' });\n // This hook converts CoffeeScript source code into JavaScript source code\n // for all imported CoffeeScript files.\n const transformedSource = coffeescript.compile(rawSource.toString(), url);\n\n // To determine how Node.js would interpret the transpilation result,\n // search up the file system for the nearest parent package.json file\n // and read its \"type\" field.\n return {\n format: await getPackageType(url),\n shortCircuit: true,\n source: transformedSource,\n };\n }\n\n // Let Node.js handle all other URLs.\n return nextLoad(url, context);\n}\n\nasync function getPackageType(url) {\n // `url` is only a file path during the first iteration when passed the\n // resolved url from the load() hook\n // an actual file path from load() will contain a file extension as it's\n // required by the spec\n // this simple truthy check for whether `url` contains a file extension will\n // work for most projects but does not cover some edge-cases (such as\n // extensionless files or a url ending in a trailing space)\n const pJson = findPackageJSON(url);\n\n return readFile(pJson, 'utf8')\n .then(JSON.parse)\n .then((json) => json?.type)\n .catch(() => undefined);\n}\n",
"displayName": "Asynchronous version"
},
{
"textRaw": "Synchronous version",
"name": "synchronous_version",
"type": "module",
"desc": "// coffeescript-sync-hooks.mjs\nimport { readFileSync } from 'node:fs';\nimport { registerHooks, findPackageJSON } from 'node:module';\nimport coffeescript from 'coffeescript';\n\nconst extensionsRegex = /\\.(coffee|litcoffee|coffee\\.md)$/;\n\nfunction load(url, context, nextLoad) {\n if (extensionsRegex.test(url)) {\n const { source: rawSource } = nextLoad(url, { ...context, format: 'coffee' });\n const transformedSource = coffeescript.compile(rawSource.toString(), url);\n\n return {\n format: getPackageType(url),\n shortCircuit: true,\n source: transformedSource,\n };\n }\n\n return nextLoad(url, context);\n}\n\nfunction getPackageType(url) {\n const pJson = findPackageJSON(url);\n if (!pJson) {\n return undefined;\n }\n try {\n const file = readFileSync(pJson, 'utf-8');\n return JSON.parse(file)?.type;\n } catch {\n return undefined;\n }\n}\n\nregisterHooks({ load });\n",
"displayName": "Synchronous version"
}
],
"displayName": "Transpilation"
},
{
"textRaw": "Running hooks",
"name": "running_hooks",
"type": "module",
"desc": "# main.coffee\nimport { scream } from './scream.coffee'\nconsole.log scream 'hello, world'\n\nimport { version } from 'node:process'\nconsole.log \"Brought to you by Node.js version #{version}\"\n\n# scream.coffee\nexport scream = (str) -> str.toUpperCase()\n\nFor the sake of running the example, add a package.json file containing the\nmodule type of the CoffeeScript files.
{\n \"type\": \"module\"\n}\n\nThis is only for running the example. In real world loaders, getPackageType() must be\nable to return an format known to Node.js even in the absence of an explicit type in a\npackage.json, or otherwise the nextLoad call would throw ERR_UNKNOWN_FILE_EXTENSION\n(if undefined) or ERR_UNKNOWN_MODULE_FORMAT (if it's not a known format listed in\nthe load hook documentation).
With the preceding hooks modules, running\nnode --import 'data:text/javascript,import { register } from \"node:module\"; import { pathToFileURL } from \"node:url\"; register(pathToFileURL(\"./coffeescript-hooks.mjs\"));' ./main.coffee\nor node --import ./coffeescript-sync-hooks.mjs ./main.coffee\ncauses main.coffee to be turned into JavaScript after its source code is\nloaded from disk but before Node.js executes it; and so on for any .coffee,\n.litcoffee or .coffee.md files referenced via import statements of any\nloaded file.
The previous two examples defined load hooks. This is an example of a\nresolve hook. This hooks module reads an import-map.json file that defines\nwhich specifiers to override to other URLs (this is a very simplistic\nimplementation of a small subset of the \"import maps\" specification).
// import-map-hooks.js\nimport fs from 'node:fs/promises';\n\nconst { imports } = JSON.parse(await fs.readFile('import-map.json'));\n\nexport async function resolve(specifier, context, nextResolve) {\n if (Object.hasOwn(imports, specifier)) {\n return nextResolve(imports[specifier], context);\n }\n\n return nextResolve(specifier, context);\n}\n",
"displayName": "Asynchronous version"
},
{
"textRaw": "Synchronous version",
"name": "synchronous_version",
"type": "module",
"desc": "// import-map-sync-hooks.js\nimport fs from 'node:fs/promises';\nimport module from 'node:module';\n\nconst { imports } = JSON.parse(fs.readFileSync('import-map.json', 'utf-8'));\n\nfunction resolve(specifier, context, nextResolve) {\n if (Object.hasOwn(imports, specifier)) {\n return nextResolve(imports[specifier], context);\n }\n\n return nextResolve(specifier, context);\n}\n\nmodule.registerHooks({ resolve });\n",
"displayName": "Synchronous version"
},
{
"textRaw": "Using the hooks",
"name": "using_the_hooks",
"type": "module",
"desc": "With these files:
\n// main.js\nimport 'a-module';\n\n// import-map.json\n{\n \"imports\": {\n \"a-module\": \"./some-module.js\"\n }\n}\n\n// some-module.js\nconsole.log('some module!');\n\nRunning node --import 'data:text/javascript,import { register } from \"node:module\"; import { pathToFileURL } from \"node:url\"; register(pathToFileURL(\"./import-map-hooks.js\"));' main.js\nor node --import ./import-map-sync-hooks.js main.js\nshould print some module!.