{ "type": "module", "source": "doc/api/module.md", "modules": [ { "textRaw": "Modules: `node:module` API", "name": "modules:_`node:module`_api", "introduced_in": "v12.20.0", "meta": { "added": [ "v0.3.7" ], "changes": [] }, "modules": [ { "textRaw": "The `Module` object", "name": "the_`module`_object", "desc": "\n

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').

", "properties": [ { "textRaw": "`builtinModules` {string\\[]}", "type": "string\\[]", "name": "builtinModules", "meta": { "added": [ "v9.3.0", "v8.10.0", "v6.13.0" ], "changes": [] }, "desc": "

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.

\n

module in this context isn't the same object that's provided\nby the module wrapper. To access it, require the Module module:

\n
// 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)`", "type": "method", "name": "createRequire", "meta": { "added": [ "v12.2.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {require} Require function", "name": "return", "type": "require", "desc": "Require function" }, "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." } ] } ], "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.isBuiltin(moduleName)`", "type": "method", "name": "isBuiltin", "meta": { "added": [ "v18.6.0" ], "changes": [] }, "signatures": [ { "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" }, "params": [ { "textRaw": "`moduleName` {string} name of the module", "name": "moduleName", "type": "string", "desc": "name of the module" } ] } ], "desc": "
import { isBuiltin } from 'node:module';\nisBuiltin('node:fs'); // true\nisBuiltin('fs'); // true\nisBuiltin('wss'); // false\n
" }, { "textRaw": "`module.register(specifier[, parentURL][, options])`", "type": "method", "name": "register", "meta": { "added": [ "v18.19.0" ], "changes": [ { "version": "v18.19.0", "pr-url": "https://github.com/nodejs/node/pull/49655", "description": "Add support for WHATWG URL instances." } ] }, "stability": 1, "stabilityText": ".1 - 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." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "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\\[]} [transferrable objects][] to be passed into the `initialize` hook.", "name": "transferList", "type": "Object\\[]", "desc": "[transferrable objects][] to be passed into the `initialize` hook." } ] } ] } ], "desc": "

Register a module that exports hooks that customize Node.js module\nresolution and loading behavior. See Customization hooks.

" }, { "textRaw": "`module.syncBuiltinESMExports()`", "type": "method", "name": "syncBuiltinESMExports", "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.

\n
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
\n

" } ], "type": "module", "displayName": "The `Module` object" }, { "textRaw": "Source map v3 support", "name": "source_map_v3_support", "meta": { "added": [ "v13.7.0", "v12.17.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

Helpers for interacting with the source map cache. This cache is\npopulated when source map parsing is enabled and\nsource map include directives are found in a modules' footer.

\n

To 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.

\n
// 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
\n\n

", "methods": [ { "textRaw": "`module.findSourceMap(path)`", "type": "method", "name": "findSourceMap", "meta": { "added": [ "v13.7.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "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." }, "params": [ { "textRaw": "`path` {string}", "name": "path", "type": "string" } ] } ], "desc": "

path is the resolved path for the file for which a corresponding source map\nshould be fetched.

" } ], "classes": [ { "textRaw": "Class: `module.SourceMap`", "type": "class", "name": "module.SourceMap", "meta": { "added": [ "v13.7.0", "v12.17.0" ], "changes": [] }, "properties": [ { "textRaw": "`payload` Returns: {Object}", "type": "Object", "name": "return", "desc": "

Getter for the payload used to construct the SourceMap instance.

" } ], "methods": [ { "textRaw": "`sourceMap.findEntry(lineOffset, columnOffset)`", "type": "method", "name": "findEntry", "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [ { "textRaw": "`lineOffset` {number} The zero-indexed line number offset in the generated source", "name": "lineOffset", "type": "number", "desc": "The zero-indexed line number offset in the generated source" }, { "textRaw": "`columnOffset` {number} The zero-indexed column number offset in the generated source", "name": "columnOffset", "type": "number", "desc": "The zero-indexed column number offset in the generated source" } ] } ], "desc": "

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.

\n

The object returned contains the following keys:

\n\n

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.

\n

To 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)

" }, { "textRaw": "`sourceMap.findOrigin(lineNumber, columnNumber)`", "type": "method", "name": "findOrigin", "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [ { "textRaw": "`lineNumber` {number} The 1-indexed line number of the call site in the generated source", "name": "lineNumber", "type": "number", "desc": "The 1-indexed line number of the call site in the generated source" }, { "textRaw": "`columnOffset` {number} The 1-indexed column number of the call site in the generated source", "name": "columnOffset", "type": "number", "desc": "The 1-indexed column number of the call site in the generated source" } ] } ], "desc": "

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.

\n

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:

\n" } ], "signatures": [ { "params": [ { "textRaw": "`payload` {Object}", "name": "payload", "type": "Object" } ], "desc": "

Creates a new sourceMap instance.

\n

payload is an object with keys matching the Source map v3 format:

\n" } ] } ], "type": "module", "displayName": "Source map v3 support" } ], "stability": 1, "stabilityText": ".1 - Active development", "miscs": [ { "textRaw": "Customization Hooks", "name": "Customization Hooks", "meta": { "added": [ "v8.8.0" ], "changes": [ { "version": "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." } ] }, "stability": 1, "stabilityText": ".1 - Active development", "type": "misc", "desc": "

", "miscs": [ { "textRaw": "Enabling", "name": "enabling", "desc": "

Module resolution and loading can be customized by registering a file which\nexports a set of hooks. This can be done using the register method\nfrom node:module, which you can run before your application code by\nusing the --import flag:

\n
node --import ./register-hooks.js ./my-app.js\n
\n
// register-hooks.js\nimport { register } from 'node:module';\n\nregister('./hooks.mjs', import.meta.url);\n
\n
// register-hooks.js\nconst { register } = require('node:module');\nconst { pathToFileURL } = require('node:url');\n\nregister('./hooks.mjs', pathToFileURL(__filename));\n
\n

The file passed to --import can also be an export from a dependency:

\n
node --import some-package/register ./my-app.js\n
\n

Where some-package has an \"exports\" field defining the /register\nexport to map to a file that calls register(), like the following register-hooks.js\nexample.

\n

Using --import ensures that the hooks are registered before any application\nfiles are imported, including the entry point of the application. Alternatively,\nregister can be called from the entry point, but dynamic import() must be\nused for any code that should be run after the hooks are registered:

\n
import { register } from 'node:module';\n\nregister('http-to-https', import.meta.url);\n\n// Because this is a dynamic `import()`, the `http-to-https` hooks will run\n// to handle `./my-app.js` and any other files it imports or requires.\nawait import('./my-app.js');\n
\n
const { register } = require('node:module');\nconst { pathToFileURL } = require('node:url');\n\nregister('http-to-https', pathToFileURL(__filename));\n\n// Because this is a dynamic `import()`, the `http-to-https` hooks will run\n// to handle `./my-app.js` and any other files it imports or requires.\nimport('./my-app.js');\n
\n

In this example, we are registering the http-to-https hooks, but they will\nonly be available for subsequently imported modules—in this case, my-app.js\nand anything it references via import (and optionally require). If the\nimport('./my-app.js') had instead been a static import './my-app.js', the\napp would have already been loaded before the http-to-https hooks were\nregistered. This due to the ES modules specification, where static imports are\nevaluated from the leaves of the tree first, then back to the trunk. There can\nbe static imports within my-app.js, which will not be evaluated until\nmy-app.js is dynamically imported.

\n

my-app.js can also be CommonJS. Customization hooks will run for any\nmodules that it references via import (and optionally require).

\n

Finally, if all you want to do is register hooks before your app runs and you\ndon't want to create a separate file for that purpose, you can pass a data:\nURL to --import:

\n
node --import 'data:text/javascript,import { register } from \"node:module\"; import { pathToFileURL } from \"node:url\"; register(\"http-to-https\", pathToFileURL(\"./\"));' ./my-app.js\n
", "type": "misc", "displayName": "Enabling" }, { "textRaw": "Chaining", "name": "chaining", "desc": "

It's possible to call register more than once:

\n
// entrypoint.mjs\nimport { register } from 'node:module';\n\nregister('./first.mjs', import.meta.url);\nregister('./second.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('./first.mjs', parentURL);\nregister('./second.mjs', parentURL);\nimport('./my-app.mjs');\n
\n

In this example, the registered hooks will form chains. If both first.mjs and\nsecond.mjs define a resolve hook, both will be called, in the order they\nwere registered. The same applies to all the other hooks.

\n

The registered hooks also affect register itself. In this example,\nsecond.mjs will be resolved and loaded per the hooks registered by\nfirst.mjs. This allows for things like writing hooks in non-JavaScript\nlanguages, so long as an earlier registered loader is one that transpiles into\nJavaScript.

\n

The register method cannot be called from within the module that defines the\nhooks.

", "type": "misc", "displayName": "Chaining" }, { "textRaw": "Communication with module customization hooks", "name": "communication_with_module_customization_hooks", "desc": "

Module customization 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.

\n

The register method can be used to pass data to an initialize hook. The\ndata passed to the hook may include transferrable objects like ports.

\n
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});\n\nregister('./my-hooks.mjs', {\n  parentURL: import.meta.url,\n  data: { number: 1, port: port2 },\n  transferList: [port2],\n});\n
\n
const { 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});\n\nregister('./my-hooks.mjs', {\n  parentURL: pathToFileURL(__filename),\n  data: { number: 1, port: port2 },\n  transferList: [port2],\n});\n
", "type": "misc", "displayName": "Communication with module customization hooks" }, { "textRaw": "Hooks", "name": "hooks", "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.

\n
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
\n

Hooks are part of a chain, even if that chain consists of only one custom\n(user-provided) hook and the default hook, which is always present. Hook\nfunctions 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.

\n

A 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.

\n

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.

", "methods": [ { "textRaw": "`initialize()`", "type": "method", "name": "initialize", "meta": { "added": [ "v18.19.0" ], "changes": [] }, "stability": 1, "stabilityText": ".1 - Active development", "signatures": [ { "params": [ { "textRaw": "`data` {any} The data from `register(loader, import.meta.url, { data })`.", "name": "data", "type": "any", "desc": "The data from `register(loader, import.meta.url, { data })`." } ] } ], "desc": "

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.

\n

This hook can receive data from a register invocation, including\nports and other transferrable 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.

\n

Module customization code:

\n
// path-to-my-hooks.js\n\nexport async function initialize({ number, port }) {\n  port.postMessage(`increment: ${number + 1}`);\n}\n
\n

Caller code:

\n
import 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});\n\nregister('./path-to-my-hooks.js', {\n  parentURL: import.meta.url,\n  data: { number: 1, port: port2 },\n  transferList: [port2],\n});\n
\n
const 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});\n\nregister('./path-to-my-hooks.js', {\n  parentURL: pathToFileURL(__filename),\n  data: { number: 1, port: port2 },\n  transferList: [port2],\n});\n
" }, { "textRaw": "`resolve(specifier, context, nextResolve)`", "type": "method", "name": "resolve", "meta": { "changes": [ { "version": "v18.19.0", "pr-url": "https://github.com/nodejs/node/pull/50140", "description": "The property `context.importAssertions` is replaced with `context.importAttributes`. Using the old name is still supported and will emit an experimental warning." }, { "version": [ "v18.6.0", "v16.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/42623", "description": "Add support for chaining resolve hooks. Each hook must either call `nextResolve()` or include a `shortCircuit` property set to `true` in its return." }, { "version": [ "v17.1.0", "v16.14.0" ], "pr-url": "https://github.com/nodejs/node/pull/40250", "description": "Add support for import assertions." } ] }, "stability": 1, "stabilityText": ".2 - Release candidate", "signatures": [ { "return": { "textRaw": "Returns: {Object|Promise}", "name": "return", "type": "Object|Promise", "options": [ { "textRaw": "`format` {string|null|undefined} A hint to the load hook (it might be ignored) `'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'`", "name": "format", "type": "string|null|undefined", "desc": "A hint to the load hook (it might be ignored) `'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'`" }, { "textRaw": "`importAttributes` {Object|undefined} The import attributes to use when caching the module (optional; if excluded the input will be used)", "name": "importAttributes", "type": "Object|undefined", "desc": "The import attributes to use when caching the module (optional; if excluded the input will be used)" }, { "textRaw": "`shortCircuit` {undefined|boolean} A signal that this hook intends to terminate the chain of `resolve` hooks. **Default:** `false`", "name": "shortCircuit", "type": "undefined|boolean", "default": "`false`", "desc": "A signal that this hook intends to terminate the chain of `resolve` hooks." }, { "textRaw": "`url` {string} The absolute URL to which this input resolves", "name": "url", "type": "string", "desc": "The absolute URL to which this input resolves" } ] }, "params": [ { "textRaw": "`specifier` {string}", "name": "specifier", "type": "string" }, { "textRaw": "`context` {Object}", "name": "context", "type": "Object", "options": [ { "textRaw": "`conditions` {string\\[]} Export conditions of the relevant `package.json`", "name": "conditions", "type": "string\\[]", "desc": "Export conditions of the relevant `package.json`" }, { "textRaw": "`importAttributes` {Object} An object whose key-value pairs represent the attributes for the module to import", "name": "importAttributes", "type": "Object", "desc": "An object whose key-value pairs represent the attributes for the module to import" }, { "textRaw": "`parentURL` {string|undefined} The module importing this one, or undefined if this is the Node.js entry point", "name": "parentURL", "type": "string|undefined", "desc": "The module importing this one, or undefined if this is the Node.js entry point" } ] }, { "textRaw": "`nextResolve` {Function} The subsequent `resolve` hook in the chain, or the Node.js default `resolve` hook after the last user-supplied `resolve` hook", "name": "nextResolve", "type": "Function", "desc": "The subsequent `resolve` hook in the chain, or the Node.js default `resolve` hook after the last user-supplied `resolve` hook", "options": [ { "textRaw": "`specifier` {string}", "name": "specifier", "type": "string" }, { "textRaw": "`context` {Object}", "name": "context", "type": "Object" } ] } ] } ], "desc": "
\n

Warning Despite support for returning promises and async functions, calls\nto resolve may block the main thread which can impact performance.

\n
\n

The 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.

\n

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.

\n

The conditions property in context is an array of conditions for\npackage exports conditions that apply to this resolution\nrequest. They can be used for looking up conditional mappings elsewhere or to\nmodify the list when calling the default resolution logic.

\n

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.

\n
export async function resolve(specifier, context, nextResolve) {\n  const { parentURL = null } = context;\n\n  if (Math.random() > 0.5) { // Some condition.\n    // For some or all specifiers, do some custom logic for resolving.\n    // Always return an object of the form {url: <string>}.\n    return {\n      shortCircuit: true,\n      url: parentURL ?\n        new URL(specifier, parentURL).href :\n        new URL(specifier).href,\n    };\n  }\n\n  if (Math.random() < 0.5) { // Another condition.\n    // When calling `defaultResolve`, the arguments can be modified. In this\n    // case it's adding another value for matching conditional exports.\n    return nextResolve(specifier, {\n      ...context,\n      conditions: [...context.conditions, 'another-condition'],\n    });\n  }\n\n  // 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
" }, { "textRaw": "`load(url, context, nextLoad)`", "type": "method", "name": "load", "meta": { "changes": [ { "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." } ] }, "stability": 1, "stabilityText": ".2 - Release candidate", "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`format` {string}", "name": "format", "type": "string" }, { "textRaw": "`shortCircuit` {undefined|boolean} A signal that this hook intends to terminate the chain of `resolve` hooks. **Default:** `false`", "name": "shortCircuit", "type": "undefined|boolean", "default": "`false`", "desc": "A signal that this hook intends to terminate the chain of `resolve` hooks." }, { "textRaw": "`source` {string|ArrayBuffer|TypedArray} The source for Node.js to evaluate", "name": "source", "type": "string|ArrayBuffer|TypedArray", "desc": "The source for Node.js to evaluate" } ] }, "params": [ { "textRaw": "`url` {string} The URL returned by the `resolve` chain", "name": "url", "type": "string", "desc": "The URL returned by the `resolve` chain" }, { "textRaw": "`context` {Object}", "name": "context", "type": "Object", "options": [ { "textRaw": "`conditions` {string\\[]} Export conditions of the relevant `package.json`", "name": "conditions", "type": "string\\[]", "desc": "Export conditions of the relevant `package.json`" }, { "textRaw": "`format` {string|null|undefined} The format optionally supplied by the `resolve` hook chain", "name": "format", "type": "string|null|undefined", "desc": "The format optionally supplied by the `resolve` hook chain" }, { "textRaw": "`importAttributes` {Object}", "name": "importAttributes", "type": "Object" } ] }, { "textRaw": "`nextLoad` {Function} The subsequent `load` hook in the chain, or the Node.js default `load` hook after the last user-supplied `load` hook", "name": "nextLoad", "type": "Function", "desc": "The subsequent `load` hook in the chain, or the Node.js default `load` hook after the last user-supplied `load` hook", "options": [ { "textRaw": "`specifier` {string}", "name": "specifier", "type": "string" }, { "textRaw": "`context` {Object}", "name": "context", "type": "Object" } ] } ] } ], "desc": "

The load hook provides a way to define a custom method of determining how a\nURL should be interpreted, retrieved, and parsed. It is also in charge of\nvalidating the import assertion.

\n

The final value of format must be one of the following:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
formatDescriptionAcceptable types for source returned by load
'builtin'Load a Node.js builtin moduleNot applicable
'commonjs'Load a Node.js CommonJS moduleNot applicable
'json'Load a JSON file{ string, ArrayBuffer, TypedArray }
'module'Load an ES module{ string, ArrayBuffer, TypedArray }
'wasm'Load a WebAssembly module{ ArrayBuffer, TypedArray }
\n

The value of source is ignored for type 'builtin' because currently it is\nnot possible to replace the value of a Node.js builtin (core) module. The value\nof source is ignored for type 'commonjs' because the CommonJS module loader\ndoes not provide a mechanism for the ES module loader to override the\nCommonJS module return value. This limitation\nmight be overcome in the future.

\n
\n

Warning: The ESM load hook and namespaced exports from CommonJS modules\nare incompatible. Attempting to use them together will result in an empty\nobject from the import. This may be addressed in the future.

\n
\n
\n

These types all correspond to classes defined in ECMAScript.

\n
\n\n

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.

\n

The 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.

\n
export async function load(url, context, nextLoad) {\n  const { format } = context;\n\n  if (Math.random() > 0.5) { // Some condition\n    /*\n      For some or all URLs, do some custom logic for retrieving the source.\n      Always return an object of the form {\n        format: <string>,\n        source: <string|buffer>,\n      }.\n    */\n    return {\n      format,\n      shortCircuit: true,\n      source: '...',\n    };\n  }\n\n  // Defer to the next hook in the chain.\n  return nextLoad(url);\n}\n
\n

In a more advanced scenario, this can also be used to transform an unsupported\nsource to a supported one (see Examples below).

" }, { "textRaw": "`globalPreload()`", "type": "method", "name": "globalPreload", "meta": { "changes": [ { "version": [ "v18.6.0", "v16.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/42623", "description": "Add support for chaining globalPreload hooks." } ] }, "stability": 1, "stabilityText": ".0 - Early development", "signatures": [ { "params": [] } ], "desc": "
\n

Warning: This hook will be removed in a future version. Use\ninitialize instead. When a hooks module has an initialize export,\nglobalPreload will be ignored.

\n
\n\n

Sometimes it might be necessary to run some code inside of the same global\nscope that the application runs in. This hook allows the return of a string\nthat is run as a sloppy-mode script on startup.

\n

Similar to how CommonJS wrappers work, the code runs in an implicit function\nscope. The only argument is a require-like function that can be used to load\nbuiltins like \"fs\": getBuiltin(request: string).

\n

If the code needs more advanced require features, it has to construct\nits own require using module.createRequire().

\n
export function globalPreload(context) {\n  return `\\\nglobalThis.someInjectedProperty = 42;\nconsole.log('I just set some globals!');\n\nconst { createRequire } = getBuiltin('module');\nconst { cwd } = getBuiltin('process');\n\nconst require = createRequire(cwd() + '/<preload>');\n// [...]\n`;\n}\n
\n

Another argument is provided to the preload code: port. This is available as a\nparameter to the hook and inside of the source text returned by the hook. This\nfunctionality has been moved to the initialize hook.

\n

Care must be taken in order to properly call port.ref() and\nport.unref() to prevent a process from being in a state where it won't\nclose normally.

\n
/**\n * This example has the application context send a message to the hook\n * and sends the message back to the application context\n */\nexport function globalPreload({ port }) {\n  port.on('message', (msg) => {\n    port.postMessage(msg);\n  });\n  return `\\\n    port.postMessage('console.log(\"I went to the hook and back\");');\n    port.on('message', (msg) => {\n      eval(msg);\n    });\n  `;\n}\n
\n

Examples

\n

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", "desc": "

In current Node.js, specifiers starting with https:// are experimental (see\nHTTPS and HTTP imports).

\n

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
\n

With 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.

", "type": "module", "displayName": "Import from HTTPS" }, { "textRaw": "Transpilation", "name": "transpilation", "desc": "

Sources that are in formats Node.js doesn't understand can be converted into\nJavaScript using the load hook.

\n

This is less performant than transpiling source files before running Node.js;\ntranspiler hooks should only be used for development and testing purposes.

\n
// coffeescript-hooks.mjs\nimport { readFile } from 'node:fs/promises';\nimport { dirname, extname, resolve as resolvePath } from 'node:path';\nimport { cwd } from 'node:process';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\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, so we want any\n    // CoffeeScript file to be treated by Node.js the same as a .js file at the\n    // same location. To determine how Node.js would interpret an arbitrary .js\n    // file, search up the file system for the nearest parent package.json file\n    // and read its \"type\" field.\n    const format = await getPackageType(url);\n\n    const { source: rawSource } = await nextLoad(url, { ...context, format });\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    return {\n      format,\n      shortCircuit: true,\n      source: transformedSource,\n    };\n  }\n\n  // Let Node.js handle all other URLs.\n  return nextLoad(url);\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 isFilePath = !!extname(url);\n  // If it is a file path, get the directory it's in\n  const dir = isFilePath ?\n    dirname(fileURLToPath(url)) :\n    url;\n  // Compose a file path to a package.json in the same directory,\n  // which may or may not exist\n  const packagePath = resolvePath(dir, 'package.json');\n  // Try to read the possibly nonexistent package.json\n  const type = await readFile(packagePath, { encoding: 'utf8' })\n    .then((filestring) => JSON.parse(filestring).type)\n    .catch((err) => {\n      if (err?.code !== 'ENOENT') console.error(err);\n    });\n  // Ff package.json existed and contained a `type` field with a value, voila\n  if (type) return type;\n  // Otherwise, (if not at the root) continue checking the next directory up\n  // If at the root, stop and return false\n  return dir.length > 1 && getPackageType(resolvePath(dir, '..'));\n}\n
\n
# 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
\n

With the preceding hooks module, running\nnode --import 'data:text/javascript,import { register } from \"node:module\"; import { pathToFileURL } from \"node:url\"; register(pathToFileURL(\"./coffeescript-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.

", "type": "module", "displayName": "Transpilation" }, { "textRaw": "Import maps", "name": "import_maps", "desc": "

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).

\n
// 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
\n

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
\n

Running node --import 'data:text/javascript,import { register } from \"node:module\"; import { pathToFileURL } from \"node:url\"; register(pathToFileURL(\"./import-map-hooks.js\"));' main.js\nshould print some module!.

", "type": "module", "displayName": "Import maps" } ], "type": "misc", "displayName": "Hooks" } ] } ], "type": "module", "displayName": "Modules: `node:module` API" } ] }