{
  "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": "<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" class=\"type\">&lt;Object&gt;</a></li>\n</ul>\n<p>Provides general utility methods when interacting with instances of\n<code>Module</code>, the <a href=\"modules.html#the-module-object\"><code>module</code></a> variable often seen in <a href=\"modules.html\">CommonJS</a> modules. Accessed\nvia <code>import 'node:module'</code> or <code>require('node:module')</code>.</p>",
          "properties": [
            {
              "textRaw": "`builtinModules` {string\\[]}",
              "type": "string\\[]",
              "name": "builtinModules",
              "meta": {
                "added": [
                  "v9.3.0",
                  "v8.10.0",
                  "v6.13.0"
                ],
                "changes": []
              },
              "desc": "<p>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.</p>\n<p><code>module</code> in this context isn't the same object that's provided\nby the <a href=\"modules.html#the-module-wrapper\">module wrapper</a>. To access it, require the <code>Module</code> module:</p>\n<pre><code class=\"language-mjs\">// module.mjs\n// In an ECMAScript module\nimport { builtinModules as builtin } from 'node:module';\n</code></pre>\n<pre><code class=\"language-cjs\">// module.cjs\n// In a CommonJS module\nconst builtin = require('node:module').builtinModules;\n</code></pre>"
            }
          ],
          "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": "<pre><code class=\"language-mjs\">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</code></pre>"
            },
            {
              "textRaw": "`module.isBuiltin(moduleName)`",
              "type": "method",
              "name": "isBuiltin",
              "meta": {
                "added": [
                  "v18.6.0",
                  "v16.17.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": "<pre><code class=\"language-mjs\">import { isBuiltin } from 'node:module';\nisBuiltin('node:fs'); // true\nisBuiltin('fs'); // true\nisBuiltin('wss'); // false\n</code></pre>"
            },
            {
              "textRaw": "`module.register(specifier[, parentURL][, options])`",
              "type": "method",
              "name": "register",
              "meta": {
                "added": [
                  "REPLACEME"
                ],
                "changes": []
              },
              "stability": 1,
              "stabilityText": ".1 - Active development",
              "signatures": [
                {
                  "return": {
                    "textRaw": "Returns: {any} returns whatever was returned by the `initialize` hook.",
                    "name": "return",
                    "type": "any",
                    "desc": "returns whatever was returned by the `initialize` hook."
                  },
                  "params": [
                    {
                      "textRaw": "`specifier` {string} 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",
                      "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} 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",
                      "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": "<p>Register a module that exports <a href=\"#customization-hooks\">hooks</a> that customize Node.js module\nresolution and loading behavior.</p>\n<pre><code class=\"language-mjs\">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// before importing `./my-app.mjs`.\nawait import('./my-app.mjs');\n</code></pre>\n<p>In the example above, we are registering the <code>http-to-https</code> loader,\nbut it will only be available for subsequently imported modules—in\nthis case, <code>my-app.mjs</code>. If the <code>await import('./my-app.mjs')</code> had\ninstead been a static <code>import './my-app.mjs'</code>, <em>the app would already\nhave been loaded</em> before the <code>http-to-https</code> hooks were\nregistered. This is part of the design of ES modules, where static\nimports are evaluated from the leaves of the tree first back to the\ntrunk. There can be static imports <em>within</em> <code>my-app.mjs</code>, which\nwill not be evaluated until <code>my-app.mjs</code> is when it's dynamically\nimported.</p>\n<p>The <code>--experimental-loader</code> flag of the CLI can be used together\nwith the <code>register</code> function; the hooks registered with the\nfunction will follow the same evaluation chain of hooks registered\nwithin the CLI:</p>\n<pre><code class=\"language-console\">node \\\n  --experimental-loader unpkg \\\n  --experimental-loader http-to-https \\\n  --experimental-loader cache-buster \\\n  entrypoint.mjs\n</code></pre>\n<pre><code class=\"language-mjs\">// entrypoint.mjs\nimport { URL } from 'node:url';\nimport { register } from 'node:module';\n\nconst loaderURL = new URL('./my-programmatically-loader.mjs', import.meta.url);\n\nregister(loaderURL);\nawait import('./my-app.mjs');\n</code></pre>\n<p>The <code>my-programmatic-loader.mjs</code> can leverage <code>unpkg</code>,\n<code>http-to-https</code>, and <code>cache-buster</code> loaders.</p>\n<p>It's also possible to use <code>register</code> more than once:</p>\n<pre><code class=\"language-mjs\">// entrypoint.mjs\nimport { URL } from 'node:url';\nimport { register } from 'node:module';\n\nregister(new URL('./first-loader.mjs', import.meta.url));\nregister('./second-loader.mjs', import.meta.url);\nawait import('./my-app.mjs');\n</code></pre>\n<p>Both loaders (<code>first-loader.mjs</code> and <code>second-loader.mjs</code>) can use\nall the resources provided by the loaders registered in the CLI. But\nremember that they will only be available in the next imported\nmodule (<code>my-app.mjs</code>). The evaluation order of the hooks when\nimporting <code>my-app.mjs</code> and consecutive modules in the example above\nwill be:</p>\n<pre><code class=\"language-console\">resolve: second-loader.mjs\nresolve: first-loader.mjs\nresolve: cache-buster\nresolve: http-to-https\nresolve: unpkg\nload: second-loader.mjs\nload: first-loader.mjs\nload: cache-buster\nload: http-to-https\nload: unpkg\nglobalPreload: second-loader.mjs\nglobalPreload: first-loader.mjs\nglobalPreload: cache-buster\nglobalPreload: http-to-https\nglobalPreload: unpkg\n</code></pre>\n<p>This function can also be used to pass data to the loader's <a href=\"#initialize\"><code>initialize</code></a>\nhook; the data passed to the hook may include transferrable objects like ports.</p>\n<pre><code class=\"language-mjs\">import { register } from 'node:module';\nimport { MessageChannel } from 'node:worker_threads';\n\n// This example showcases how a message channel can be used to\n// communicate to the loader, by sending `port2` to the loader.\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (msg) => {\n  console.log(msg);\n});\n\nregister('./my-programmatic-loader.mjs', {\n  parentURL: import.meta.url,\n  data: { number: 1, port: port2 },\n  transferList: [port2],\n});\n</code></pre>"
            },
            {
              "textRaw": "`module.syncBuiltinESMExports()`",
              "type": "method",
              "name": "syncBuiltinESMExports",
              "meta": {
                "added": [
                  "v12.12.0"
                ],
                "changes": []
              },
              "signatures": [
                {
                  "params": []
                }
              ],
              "desc": "<p>The <code>module.syncBuiltinESMExports()</code> method updates all the live bindings for\nbuiltin <a href=\"esm.html\">ES Modules</a> to match the properties of the <a href=\"modules.html\">CommonJS</a> exports. It\ndoes not add or remove exported names from the <a href=\"esm.html\">ES Modules</a>.</p>\n<pre><code class=\"language-js\">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</code></pre>"
            }
          ],
          "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": "<p>Helpers for interacting with the source map cache. This cache is\npopulated when source map parsing is enabled and\n<a href=\"https://sourcemaps.info/spec.html#h.lmz475t4mvbx\">source map include directives</a> are found in a modules' footer.</p>\n<p>To enable source map parsing, Node.js must be run with the flag\n<a href=\"cli.html#--enable-source-maps\"><code>--enable-source-maps</code></a>, or with code coverage enabled by setting\n<a href=\"cli.html#node_v8_coveragedir\"><code>NODE_V8_COVERAGE=dir</code></a>.</p>\n<pre><code class=\"language-mjs\">// module.mjs\n// In an ECMAScript module\nimport { findSourceMap, SourceMap } from 'node:module';\n</code></pre>\n<pre><code class=\"language-cjs\">// module.cjs\n// In a CommonJS module\nconst { findSourceMap, SourceMap } = require('node:module');\n</code></pre>\n<!-- Anchors to make sure old links find a target -->\n<p><a id=\"module_module_findsourcemap_path_error\"></a></p>",
          "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": "<p><code>path</code> is the resolved path for the file for which a corresponding source map\nshould be fetched.</p>"
            }
          ],
          "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": "<p>Getter for the payload used to construct the <a href=\"#class-modulesourcemap\"><code>SourceMap</code></a> instance.</p>"
                }
              ],
              "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": "<p>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.</p>\n<p>The object returned contains the following keys:</p>\n<ul>\n<li>generatedLine: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\">&lt;number&gt;</a> The line offset of the start of the\nrange in the generated source</li>\n<li>generatedColumn: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\">&lt;number&gt;</a> The column offset of start of the\nrange in the generated source</li>\n<li>originalSource: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string&gt;</a> The file name of the original source,\nas reported in the SourceMap</li>\n<li>originalLine: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\">&lt;number&gt;</a> The line offset of the start of the\nrange in the original source</li>\n<li>originalColumn: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\">&lt;number&gt;</a> The column offset of start of the\nrange in the original source</li>\n<li>name: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string&gt;</a></li>\n</ul>\n<p>The returned value represents the raw range as it appears in the\nSourceMap, based on zero-indexed offsets, <em>not</em> 1-indexed line and\ncolumn numbers as they appear in Error messages and CallSite\nobjects.</p>\n<p>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 <code>sourceMap.findOrigin(lineNumber, columnNumber)</code></p>"
                },
                {
                  "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": "<p>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.</p>\n<p>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:</p>\n<ul>\n<li>name: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string&gt;</a> | <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type\" class=\"type\">&lt;undefined&gt;</a> The name of the range in the\nsource map, if one was provided</li>\n<li>fileName: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string&gt;</a> The file name of the original source, as\nreported in the SourceMap</li>\n<li>lineNumber: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\">&lt;number&gt;</a> The 1-indexed lineNumber of the\ncorresponding call site in the original source</li>\n<li>columnNumber: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\">&lt;number&gt;</a> The 1-indexed columnNumber of the\ncorresponding call site in the original source</li>\n</ul>"
                }
              ],
              "signatures": [
                {
                  "params": [
                    {
                      "textRaw": "`payload` {Object}",
                      "name": "payload",
                      "type": "Object"
                    },
                    {
                      "textRaw": "`lineLengths` {number\\[]}",
                      "name": "lineLengths",
                      "type": "number\\[]"
                    }
                  ],
                  "desc": "<p>Creates a new <code>sourceMap</code> instance.</p>\n<p><code>payload</code> is an object with keys matching the <a href=\"https://sourcemaps.info/spec.html#h.mofvlxcwqzej\">Source map v3 format</a>:</p>\n<ul>\n<li><code>file</code>: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string&gt;</a></li>\n<li><code>version</code>: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\">&lt;number&gt;</a></li>\n<li><code>sources</code>: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string[]&gt;</a></li>\n<li><code>sourcesContent</code>: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string[]&gt;</a></li>\n<li><code>names</code>: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string[]&gt;</a></li>\n<li><code>mappings</code>: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string&gt;</a></li>\n<li><code>sourceRoot</code>: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string&gt;</a></li>\n</ul>\n<p><code>lineLengths</code> is an optional array of the length of each line in the\ngenerated code.</p>"
                }
              ]
            }
          ],
          "type": "module",
          "displayName": "Source map v3 support"
        }
      ],
      "stability": 1,
      "stabilityText": "Experimental",
      "miscs": [
        {
          "textRaw": "Customization Hooks",
          "name": "Customization Hooks",
          "meta": {
            "added": [
              "v8.8.0"
            ],
            "changes": [
              {
                "version": "REPLACEME",
                "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": "Experimental",
          "type": "misc",
          "desc": "<blockquote>\n<p>This API is currently being redesigned and will still change.</p>\n</blockquote>\n<p>To customize the default module resolution, loader hooks can optionally be\nprovided via a <code>--experimental-loader ./loader-name.mjs</code> argument to Node.js.</p>\n<p>When hooks are used they apply to each subsequent loader, the entry point, and\nall <code>import</code> calls. They won't apply to <code>require</code> calls; those still follow\n<a href=\"modules.html\">CommonJS</a> rules.</p>\n<p>Loaders follow the pattern of <code>--require</code>:</p>\n<pre><code class=\"language-bash\">node \\\n  --experimental-loader unpkg \\\n  --experimental-loader http-to-https \\\n  --experimental-loader cache-buster\n</code></pre>\n<p>These are called in the following sequence: <code>cache-buster</code> calls\n<code>http-to-https</code> which calls <code>unpkg</code>.</p>",
          "miscs": [
            {
              "textRaw": "Hooks",
              "name": "hooks",
              "desc": "<p>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 <code>next&#x3C;hookName>()</code>, which is a reference\nto the subsequent loader's hook.</p>\n<p>A hook that returns a value lacking a required property triggers an exception.\nA hook that returns without calling <code>next&#x3C;hookName>()</code> <em>and</em> without returning\n<code>shortCircuit: true</code> also triggers an exception. These errors are to help\nprevent unintentional breaks in the chain.</p>\n<p>Hooks are run in a separate thread, isolated from the main. That means it is a\ndifferent <a href=\"https://tc39.es/ecma262/#realm\">realm</a>. The hooks thread may be\nterminated by the main thread at any time, so do not depend on asynchronous\noperations (like <code>console.log</code>) to complete.</p>",
              "methods": [
                {
                  "textRaw": "`initialize()`",
                  "type": "method",
                  "name": "initialize",
                  "meta": {
                    "added": [
                      "REPLACEME"
                    ],
                    "changes": []
                  },
                  "signatures": [
                    {
                      "params": []
                    }
                  ],
                  "desc": "<blockquote>\n<p>The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.</p>\n</blockquote>\n<ul>\n<li><code>data</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types\" class=\"type\">&lt;any&gt;</a> The data from <code>register(loader, import.meta.url, { data })</code>.</li>\n<li>Returns: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types\" class=\"type\">&lt;any&gt;</a> The data to be returned to the caller of <code>register</code>.</li>\n</ul>\n<p>The <code>initialize</code> hook provides a way to define a custom function that runs\nin the loader's thread when the loader is initialized. Initialization happens\nwhen the loader is registered via <a href=\"#moduleregisterspecifier-parenturl-options\"><code>register</code></a> or registered via the\n<code>--experimental-loader</code> command line option.</p>\n<p>This hook can send and receive data from a <a href=\"#moduleregisterspecifier-parenturl-options\"><code>register</code></a> invocation, including\nports and other transferrable objects. The return value of <code>initialize</code> must be\neither:</p>\n<ul>\n<li><code>undefined</code>,</li>\n<li>something that can be posted as a message between threads (e.g. the input to\n<a href=\"worker_threads.html#portpostmessagevalue-transferlist\"><code>port.postMessage</code></a>),</li>\n<li>a <code>Promise</code> resolving to one of the aforementioned values.</li>\n</ul>\n<p>Loader code:</p>\n<pre><code class=\"language-mjs\">// In the below example this file is referenced as\n// '/path-to-my-loader.js'\n\nexport async function initialize({ number, port }) {\n  port.postMessage(`increment: ${number + 1}`);\n  return 'ok';\n}\n</code></pre>\n<p>Caller code:</p>\n<pre><code class=\"language-mjs\">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\n// communicate between the main (application) thread and the loader\n// running on the loaders thread, by sending `port2` to the loader.\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (msg) => {\n  assert.strictEqual(msg, 'increment: 2');\n});\n\nconst result = register('/path-to-my-loader.js', {\n  parentURL: import.meta.url,\n  data: { number: 1, port: port2 },\n  transferList: [port2],\n});\n\nassert.strictEqual(result, 'ok');\n</code></pre>"
                },
                {
                  "textRaw": "`resolve(specifier, context, nextResolve)`",
                  "type": "method",
                  "name": "resolve",
                  "meta": {
                    "changes": [
                      {
                        "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."
                      }
                    ]
                  },
                  "signatures": [
                    {
                      "params": []
                    }
                  ],
                  "desc": "<blockquote>\n<p>The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.</p>\n</blockquote>\n<ul>\n<li><code>specifier</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string&gt;</a></li>\n<li><code>context</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" class=\"type\">&lt;Object&gt;</a>\n<ul>\n<li><code>conditions</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string[]&gt;</a> Export conditions of the relevant <code>package.json</code></li>\n<li><code>importAssertions</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" class=\"type\">&lt;Object&gt;</a> An object whose key-value pairs represent the\nassertions for the module to import</li>\n<li><code>parentURL</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string&gt;</a> | <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type\" class=\"type\">&lt;undefined&gt;</a> The module importing this one, or undefined\nif this is the Node.js entry point</li>\n</ul>\n</li>\n<li><code>nextResolve</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function\" class=\"type\">&lt;Function&gt;</a> The subsequent <code>resolve</code> hook in the chain, or the\nNode.js default <code>resolve</code> hook after the last user-supplied <code>resolve</code> hook\n<ul>\n<li><code>specifier</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string&gt;</a></li>\n<li><code>context</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" class=\"type\">&lt;Object&gt;</a></li>\n</ul>\n</li>\n<li>Returns: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" class=\"type\">&lt;Object&gt;</a> | <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise\" class=\"type\">&lt;Promise&gt;</a>\n<ul>\n<li><code>format</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string&gt;</a> | <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type\" class=\"type\">&lt;null&gt;</a> | <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type\" class=\"type\">&lt;undefined&gt;</a> A hint to the load hook (it might be\nignored)\n<code>'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'</code></li>\n<li><code>importAssertions</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" class=\"type\">&lt;Object&gt;</a> | <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type\" class=\"type\">&lt;undefined&gt;</a> The import assertions to use when\ncaching the module (optional; if excluded the input will be used)</li>\n<li><code>shortCircuit</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type\" class=\"type\">&lt;undefined&gt;</a> | <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type\" class=\"type\">&lt;boolean&gt;</a> A signal that this hook intends to\nterminate the chain of <code>resolve</code> hooks. <strong>Default:</strong> <code>false</code></li>\n<li><code>url</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string&gt;</a> The absolute URL to which this input resolves</li>\n</ul>\n</li>\n</ul>\n<blockquote>\n<p><strong>Caveat</strong> Despite support for returning promises and async functions, calls\nto <code>resolve</code> may block the main thread which can impact performance.</p>\n</blockquote>\n<p>The <code>resolve</code> hook chain is responsible for telling Node.js where to find and\nhow to cache a given <code>import</code> statement or expression. It can optionally return\nits format (such as <code>'module'</code>) as a hint to the <code>load</code> hook. If a format is\nspecified, the <code>load</code> hook is ultimately responsible for providing the final\n<code>format</code> value (and it is free to ignore the hint provided by <code>resolve</code>); if\n<code>resolve</code> provides a <code>format</code>, a custom <code>load</code> hook is required even if only to\npass the value to the Node.js default <code>load</code> hook.</p>\n<p>Import type assertions are part of the cache key for saving loaded modules into\nthe internal module cache. The <code>resolve</code> hook is responsible for\nreturning an <code>importAssertions</code> object if the module should be cached with\ndifferent assertions than were present in the source code.</p>\n<p>The <code>conditions</code> property in <code>context</code> is an array of conditions for\n<a href=\"packages.html#conditional-exports\">package exports conditions</a> 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.</p>\n<p>The current <a href=\"packages.html#conditional-exports\">package exports conditions</a> are always in\nthe <code>context.conditions</code> array passed into the hook. To guarantee <em>default\nNode.js module specifier resolution behavior</em> when calling <code>defaultResolve</code>, the\n<code>context.conditions</code> array passed to it <em>must</em> include <em>all</em> elements of the\n<code>context.conditions</code> array originally passed into the <code>resolve</code> hook.</p>\n<pre><code class=\"language-mjs\">export 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: &#x3C;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() &#x3C; 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</code></pre>"
                },
                {
                  "textRaw": "`load(url, context, nextLoad)`",
                  "type": "method",
                  "name": "load",
                  "meta": {
                    "changes": [
                      {
                        "version": "REPLACEME",
                        "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."
                      }
                    ]
                  },
                  "signatures": [
                    {
                      "params": []
                    }
                  ],
                  "desc": "<blockquote>\n<p>The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.</p>\n</blockquote>\n<blockquote>\n<p>In a previous version of this API, this was split across 3 separate, now\ndeprecated, hooks (<code>getFormat</code>, <code>getSource</code>, and <code>transformSource</code>).</p>\n</blockquote>\n<ul>\n<li><code>url</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string&gt;</a> The URL returned by the <code>resolve</code> chain</li>\n<li><code>context</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" class=\"type\">&lt;Object&gt;</a>\n<ul>\n<li><code>conditions</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string[]&gt;</a> Export conditions of the relevant <code>package.json</code></li>\n<li><code>format</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string&gt;</a> | <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type\" class=\"type\">&lt;null&gt;</a> | <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type\" class=\"type\">&lt;undefined&gt;</a> The format optionally supplied by the\n<code>resolve</code> hook chain</li>\n<li><code>importAssertions</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" class=\"type\">&lt;Object&gt;</a></li>\n</ul>\n</li>\n<li><code>nextLoad</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function\" class=\"type\">&lt;Function&gt;</a> The subsequent <code>load</code> hook in the chain, or the\nNode.js default <code>load</code> hook after the last user-supplied <code>load</code> hook\n<ul>\n<li><code>specifier</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string&gt;</a></li>\n<li><code>context</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" class=\"type\">&lt;Object&gt;</a></li>\n</ul>\n</li>\n<li>Returns: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" class=\"type\">&lt;Object&gt;</a>\n<ul>\n<li><code>format</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string&gt;</a></li>\n<li><code>shortCircuit</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type\" class=\"type\">&lt;undefined&gt;</a> | <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type\" class=\"type\">&lt;boolean&gt;</a> A signal that this hook intends to\nterminate the chain of <code>resolve</code> hooks. <strong>Default:</strong> <code>false</code></li>\n<li><code>source</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string&gt;</a> | <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer\" class=\"type\">&lt;ArrayBuffer&gt;</a> | <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray\" class=\"type\">&lt;TypedArray&gt;</a> The source for Node.js to evaluate</li>\n</ul>\n</li>\n</ul>\n<p>The <code>load</code> hook provides a way to define a custom method of determining how\na URL should be interpreted, retrieved, and parsed. It is also in charge of\nvalidating the import assertion.</p>\n<p>The final value of <code>format</code> must be one of the following:</p>\n<table>\n<thead>\n<tr>\n<th><code>format</code></th>\n<th>Description</th>\n<th>Acceptable types for <code>source</code> returned by <code>load</code></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>'builtin'</code></td>\n<td>Load a Node.js builtin module</td>\n<td>Not applicable</td>\n</tr>\n<tr>\n<td><code>'commonjs'</code></td>\n<td>Load a Node.js CommonJS module</td>\n<td>{ <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String\"><code>string</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer\"><code>ArrayBuffer</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray\"><code>TypedArray</code></a>, <code>null</code>, <code>undefined</code> }</td>\n</tr>\n<tr>\n<td><code>'json'</code></td>\n<td>Load a JSON file</td>\n<td>{ <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String\"><code>string</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer\"><code>ArrayBuffer</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray\"><code>TypedArray</code></a> }</td>\n</tr>\n<tr>\n<td><code>'module'</code></td>\n<td>Load an ES module</td>\n<td>{ <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String\"><code>string</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer\"><code>ArrayBuffer</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray\"><code>TypedArray</code></a> }</td>\n</tr>\n<tr>\n<td><code>'wasm'</code></td>\n<td>Load a WebAssembly module</td>\n<td>{ <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer\"><code>ArrayBuffer</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray\"><code>TypedArray</code></a> }</td>\n</tr>\n</tbody>\n</table>\n<p>The value of <code>source</code> is ignored for type <code>'builtin'</code> because currently it is\nnot possible to replace the value of a Node.js builtin (core) module.</p>\n<p>The value of <code>source</code> can be omitted for type <code>'commonjs'</code>. When a <code>source</code> is\nprovided, all <code>require</code> calls from this module will be processed by the ESM\nloader with registered <code>resolve</code> and <code>load</code> hooks; all <code>require.resolve</code> calls\nfrom this module will be processed by the ESM loader with registered <code>resolve</code>\nhooks; <code>require.extensions</code> and monkey-patching on the CommonJS module loader\nwill not apply. If <code>source</code> is undefined or <code>null</code>, it will be handled by the\nCommonJS module loader and <code>require</code>/<code>require.resolve</code> calls will not go through\nthe registered hooks. This behavior for nullish <code>source</code> is temporary — in the\nfuture, nullish <code>source</code> will not be supported.</p>\n<p>The Node.js own <code>load</code> implementation, which is the value of <code>next</code> for the last\nloader in the <code>load</code> chain, returns <code>null</code> for <code>source</code> when <code>format</code> is\n<code>'commonjs'</code> for backward compatibility. Here is an example loader that would\nopt-in to using the non-default behavior:</p>\n<pre><code class=\"language-mjs\">import { readFile } from 'node:fs/promises';\n\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</code></pre>\n<blockquote>\n<p><strong>Caveat</strong>: The ESM <code>load</code> 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.</p>\n</blockquote>\n<blockquote>\n<p>These types all correspond to classes defined in ECMAScript.</p>\n</blockquote>\n<ul>\n<li>The specific <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer\"><code>ArrayBuffer</code></a> object is a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer\"><code>SharedArrayBuffer</code></a>.</li>\n<li>The specific <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray\"><code>TypedArray</code></a> object is a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array\"><code>Uint8Array</code></a>.</li>\n</ul>\n<p>If the source value of a text-based format (i.e., <code>'json'</code>, <code>'module'</code>)\nis not a string, it is converted to a string using <a href=\"util.html#class-utiltextdecoder\"><code>util.TextDecoder</code></a>.</p>\n<p>The <code>load</code> hook provides a way to define a custom method for retrieving the\nsource code of an ES module specifier. This would allow a loader to potentially\navoid reading files from disk. It could also be used to map an unrecognized\nformat to a supported one, for example <code>yaml</code> to <code>module</code>.</p>\n<pre><code class=\"language-mjs\">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: &#x3C;string>,\n        source: &#x3C;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</code></pre>\n<p>In a more advanced scenario, this can also be used to transform an unsupported\nsource to a supported one (see <a href=\"#examples\">Examples</a> below).</p>"
                },
                {
                  "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."
                      }
                    ]
                  },
                  "signatures": [
                    {
                      "params": []
                    }
                  ],
                  "desc": "<blockquote>\n<p>This hook will be removed in a future version. Use <a href=\"#initialize\"><code>initialize</code></a> instead.\nWhen a loader has an <code>initialize</code> export, <code>globalPreload</code> will be ignored.</p>\n</blockquote>\n<blockquote>\n<p>In a previous version of this API, this hook was named\n<code>getGlobalPreloadCode</code>.</p>\n</blockquote>\n<ul>\n<li><code>context</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" class=\"type\">&lt;Object&gt;</a> Information to assist the preload code\n<ul>\n<li><code>port</code> <a href=\"worker_threads.html#class-messageport\" class=\"type\">&lt;MessagePort&gt;</a></li>\n</ul>\n</li>\n<li>Returns: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\">&lt;string&gt;</a> Code to run before application startup</li>\n</ul>\n<p>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.</p>\n<p>Similar to how CommonJS wrappers work, the code runs in an implicit function\nscope. The only argument is a <code>require</code>-like function that can be used to load\nbuiltins like \"fs\": <code>getBuiltin(request: string)</code>.</p>\n<p>If the code needs more advanced <code>require</code> features, it has to construct\nits own <code>require</code> using  <code>module.createRequire()</code>.</p>\n<pre><code class=\"language-mjs\">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() + '/&#x3C;preload>');\n// [...]\n`;\n}\n</code></pre>\n<p>In order to allow communication between the application and the loader, another\nargument is provided to the preload code: <code>port</code>. This is available as a\nparameter to the loader hook and inside of the source text returned by the hook.\nSome care must be taken in order to properly call <a href=\"worker_threads.html#portref\"><code>port.ref()</code></a> and\n<a href=\"worker_threads.html#portunref\"><code>port.unref()</code></a> to prevent a process from being in a state where it won't\nclose normally.</p>\n<pre><code class=\"language-mjs\">/**\n * This example has the application context send a message to the loader\n * and sends the message back to the application context\n */\nexport function globalPreload({ port }) {\n  port.onmessage = (evt) => {\n    port.postMessage(evt.data);\n  };\n  return `\\\n    port.postMessage('console.log(\"I went to the Loader and back\");');\n    port.onmessage = (evt) => {\n      eval(evt.data);\n    };\n  `;\n}\n</code></pre>\n<h3>Examples</h3>\n<p>The various loader hooks can be used together to accomplish wide-ranging\ncustomizations of the Node.js code loading and evaluation behaviors.</p>"
                }
              ],
              "modules": [
                {
                  "textRaw": "HTTPS loader",
                  "name": "https_loader",
                  "desc": "<p>In current Node.js, specifiers starting with <code>https://</code> are experimental (see\n<a href=\"esm.html#https-and-http-imports\">HTTPS and HTTP imports</a>).</p>\n<p>The loader 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 this loader:\nperformance is much slower than loading files from disk, there is no caching,\nand there is no security.</p>\n<pre><code class=\"language-mjs\">// https-loader.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</code></pre>\n<pre><code class=\"language-mjs\">// main.mjs\nimport { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';\n\nconsole.log(VERSION);\n</code></pre>\n<p>With the preceding loader, running\n<code>node --experimental-loader ./https-loader.mjs ./main.mjs</code>\nprints the current version of CoffeeScript per the module at the URL in\n<code>main.mjs</code>.</p>",
                  "type": "module",
                  "displayName": "HTTPS loader"
                },
                {
                  "textRaw": "Transpiler loader",
                  "name": "transpiler_loader",
                  "desc": "<p>Sources that are in formats Node.js doesn't understand can be converted into\nJavaScript using the <a href=\"#loadurl-context-nextload\"><code>load</code> hook</a>.</p>\n<p>This is less performant than transpiling source files before running\nNode.js; a transpiler loader should only be used for development and testing\npurposes.</p>\n<pre><code class=\"language-mjs\">// coffeescript-loader.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 baseURL = pathToFileURL(`${cwd()}/`).href;\n\nexport async function load(url, context, nextLoad) {\n  if (extensionsRegex.test(url)) {\n    // Now that we patched resolve to let CoffeeScript URLs through, we need to\n    // tell Node.js what format such URLs should be interpreted as. Because\n    // CoffeeScript transpiles into JavaScript, it should be one of the two\n    // JavaScript formats: 'commonjs' or 'module'.\n\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    // When a hook returns a format of 'commonjs', `source` is ignored.\n    // To handle CommonJS files, a handler needs to be registered with\n    // `require.extensions` in order to process the files with the CommonJS\n    // loader. Avoiding the need for a separate CommonJS handler is a future\n    // enhancement planned for ES module loaders.\n    if (format === 'commonjs') {\n      return {\n        format,\n        shortCircuit: true,\n      };\n    }\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 = coffeeCompile(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 &#x26;&#x26; getPackageType(resolvePath(dir, '..'));\n}\n</code></pre>\n<pre><code class=\"language-coffee\"># 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</code></pre>\n<pre><code class=\"language-coffee\"># scream.coffee\nexport scream = (str) -> str.toUpperCase()\n</code></pre>\n<p>With the preceding loader, running\n<code>node --experimental-loader ./coffeescript-loader.mjs main.coffee</code>\ncauses <code>main.coffee</code> to be turned into JavaScript after its source code is\nloaded from disk but before Node.js executes it; and so on for any <code>.coffee</code>,\n<code>.litcoffee</code> or <code>.coffee.md</code> files referenced via <code>import</code> statements of any\nloaded file.</p>",
                  "type": "module",
                  "displayName": "Transpiler loader"
                },
                {
                  "textRaw": "\"import map\" loader",
                  "name": "\"import_map\"_loader",
                  "desc": "<p>The previous two loaders defined <code>load</code> hooks. This is an example of a loader\nthat does its work via the <code>resolve</code> hook. This loader reads an\n<code>import-map.json</code> file that specifies which specifiers to override to another\nURL (this is a very simplistic implemenation of a small subset of the\n\"import maps\" specification).</p>\n<pre><code class=\"language-mjs\">// import-map-loader.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</code></pre>\n<p>Let's assume we have these files:</p>\n<pre><code class=\"language-mjs\">// main.js\nimport 'a-module';\n</code></pre>\n<pre><code class=\"language-json\">// import-map.json\n{\n  \"imports\": {\n    \"a-module\": \"./some-module.js\"\n  }\n}\n</code></pre>\n<pre><code class=\"language-mjs\">// some-module.js\nconsole.log('some module!');\n</code></pre>\n<p>If you run <code>node --experimental-loader ./import-map-loader.js main.js</code>\nthe output will be <code>some module!</code>.</p>",
                  "type": "module",
                  "displayName": "\"import map\" loader"
                }
              ],
              "type": "misc",
              "displayName": "Hooks"
            },
            {
              "textRaw": "Register loaders programmatically",
              "name": "register_loaders_programmatically",
              "meta": {
                "added": [
                  "REPLACEME"
                ],
                "changes": []
              },
              "desc": "<p>In addition to using the <code>--experimental-loader</code> option in the CLI,\nloaders can also be registered programmatically. You can find\ndetailed information about this process in the documentation page\nfor <a href=\"#moduleregisterspecifier-parenturl-options\"><code>module.register()</code></a>.</p>",
              "type": "misc",
              "displayName": "Register loaders programmatically"
            }
          ]
        }
      ],
      "type": "module",
      "displayName": "Modules: `node:module` API"
    }
  ]
}