xref: /third_party/node/doc/api/module.html (revision 1cb0ef41)
1<!DOCTYPE html>
2<html lang="en">
3<head>
4  <meta charset="utf-8">
5  <meta name="viewport" content="width=device-width">
6  <meta name="nodejs.org:node-version" content="v18.20.1">
7  <title>Modules: node:module API | Node.js v18.20.1 Documentation</title>
8  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback">
9  <link rel="stylesheet" href="assets/style.css">
10  <link rel="stylesheet" href="assets/hljs.css">
11  <link rel="canonical" href="https://nodejs.org/api/module.html">
12  <script async defer src="assets/api.js" type="text/javascript"></script>
13  <style>@media(max-width:430px){.with-26-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}@media(max-width:574px){.with-44-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}@media(max-width:590px){.with-46-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}@media(max-width:646px){.with-53-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}</style>
14</head>
15<body class="alt apidoc" id="api-section-module">
16  <div id="content" class="clearfix">
17    <div id="column2" class="interior">
18      <div id="intro" class="interior">
19        <a href="/" title="Go back to the home page">
20          Node.js
21        </a>
22      </div>
23      <ul>
24<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
25<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
26</ul>
27<hr class="line">
28<ul>
29<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
30<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
31<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
32<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
33<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
34<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
35<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
36<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
37<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
38<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
39<li><a href="console.html" class="nav-console">Console</a></li>
40<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
41<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
42<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
43<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
44<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
45<li><a href="dns.html" class="nav-dns">DNS</a></li>
46<li><a href="domain.html" class="nav-domain">Domain</a></li>
47<li><a href="errors.html" class="nav-errors">Errors</a></li>
48<li><a href="events.html" class="nav-events">Events</a></li>
49<li><a href="fs.html" class="nav-fs">File system</a></li>
50<li><a href="globals.html" class="nav-globals">Globals</a></li>
51<li><a href="http.html" class="nav-http">HTTP</a></li>
52<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
53<li><a href="https.html" class="nav-https">HTTPS</a></li>
54<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
55<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
56<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
57<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
58<li><a href="module.html" class="nav-module active">Modules: <code>node:module</code> API</a></li>
59<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
60<li><a href="net.html" class="nav-net">Net</a></li>
61<li><a href="os.html" class="nav-os">OS</a></li>
62<li><a href="path.html" class="nav-path">Path</a></li>
63<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
64<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
65<li><a href="process.html" class="nav-process">Process</a></li>
66<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
67<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
68<li><a href="readline.html" class="nav-readline">Readline</a></li>
69<li><a href="repl.html" class="nav-repl">REPL</a></li>
70<li><a href="report.html" class="nav-report">Report</a></li>
71<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
72<li><a href="stream.html" class="nav-stream">Stream</a></li>
73<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
74<li><a href="test.html" class="nav-test">Test runner</a></li>
75<li><a href="timers.html" class="nav-timers">Timers</a></li>
76<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
77<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
78<li><a href="tty.html" class="nav-tty">TTY</a></li>
79<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
80<li><a href="url.html" class="nav-url">URL</a></li>
81<li><a href="util.html" class="nav-util">Utilities</a></li>
82<li><a href="v8.html" class="nav-v8">V8</a></li>
83<li><a href="vm.html" class="nav-vm">VM</a></li>
84<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
85<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
86<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
87<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
88<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
89</ul>
90<hr class="line">
91<ul>
92<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
93</ul>
94    </div>
95
96    <div id="column1" data-id="module" class="interior">
97      <header class="header">
98        <div class="header-container">
99          <h1>Node.js v18.20.1 documentation</h1>
100          <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden>
101            <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24">
102              <path fill="none" d="M0 0h24v24H0z" />
103              <path d="M11.1 12.08c-2.33-4.51-.5-8.48.53-10.07C6.27 2.2 1.98 6.59 1.98 12c0 .14.02.28.02.42.62-.27 1.29-.42 2-.42 1.66 0 3.18.83 4.1 2.15A4.01 4.01 0 0111 18c0 1.52-.87 2.83-2.12 3.51.98.32 2.03.5 3.11.5 3.5 0 6.58-1.8 8.37-4.52-2.36.23-6.98-.97-9.26-5.41z"/>
104              <path d="M7 16h-.18C6.4 14.84 5.3 14 4 14c-1.66 0-3 1.34-3 3s1.34 3 3 3h3c1.1 0 2-.9 2-2s-.9-2-2-2z"/>
105            </svg>
106            <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24">
107              <path d="M0 0h24v24H0z" fill="none" />
108              <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/>
109            </svg>
110          </button>
111        </div>
112        <div id="gtoc">
113          <ul>
114            <li class="pinned-header">Node.js v18.20.1</li>
115            
116    <li class="picker-header">
117      <a href="#">
118        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
119        Table of contents
120      </a>
121
122      <div class="picker"><div class="toc"><ul>
123<li><a href="#modules-nodemodule-api">Modules: <code>node:module</code> API</a>
124<ul>
125<li><a href="#the-module-object">The <code>Module</code> object</a>
126<ul>
127<li><a href="#modulebuiltinmodules"><code>module.builtinModules</code></a></li>
128<li><a href="#modulecreaterequirefilename"><code>module.createRequire(filename)</code></a></li>
129<li><a href="#moduleisbuiltinmodulename"><code>module.isBuiltin(moduleName)</code></a></li>
130<li><span class="stability_1"><a href="#moduleregisterspecifier-parenturl-options"><code>module.register(specifier[, parentURL][, options])</code></a></span></li>
131<li><a href="#modulesyncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a></li>
132</ul>
133</li>
134<li><span class="stability_1"><a href="#customization-hooks">Customization Hooks</a></span>
135<ul>
136<li><a href="#enabling">Enabling</a></li>
137<li><a href="#chaining">Chaining</a></li>
138<li><a href="#communication-with-module-customization-hooks">Communication with module customization hooks</a></li>
139<li><a href="#hooks">Hooks</a>
140<ul>
141<li><span class="stability_1"><a href="#initialize"><code>initialize()</code></a></span></li>
142<li><span class="stability_1"><a href="#resolvespecifier-context-nextresolve"><code>resolve(specifier, context, nextResolve)</code></a></span></li>
143<li><span class="stability_1"><a href="#loadurl-context-nextload"><code>load(url, context, nextLoad)</code></a></span></li>
144<li><span class="stability_1"><a href="#globalpreload"><code>globalPreload()</code></a></span></li>
145</ul>
146</li>
147<li><a href="#examples">Examples</a>
148<ul>
149<li><a href="#import-from-https">Import from HTTPS</a></li>
150<li><a href="#transpilation">Transpilation</a></li>
151<li><a href="#import-maps">Import maps</a></li>
152</ul>
153</li>
154</ul>
155</li>
156<li><span class="stability_1"><a href="#source-map-v3-support">Source map v3 support</a></span>
157<ul>
158<li><a href="#modulefindsourcemappath"><code>module.findSourceMap(path)</code></a></li>
159<li><a href="#class-modulesourcemap">Class: <code>module.SourceMap</code></a>
160<ul>
161<li><a href="#new-sourcemappayload"><code>new SourceMap(payload)</code></a></li>
162<li><a href="#sourcemappayload"><code>sourceMap.payload</code></a></li>
163<li><a href="#sourcemapfindentrylineoffset-columnoffset"><code>sourceMap.findEntry(lineOffset, columnOffset)</code></a></li>
164<li><a href="#sourcemapfindoriginlinenumber-columnnumber"><code>sourceMap.findOrigin(lineNumber, columnNumber)</code></a></li>
165</ul>
166</li>
167</ul>
168</li>
169</ul>
170</li>
171</ul></div></div>
172    </li>
173  
174            
175    <li class="picker-header">
176      <a href="#">
177        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
178        Index
179      </a>
180
181      <div class="picker"><ul>
182<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
183<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
184
185      <li>
186        <a href="index.html">Index</a>
187      </li>
188    </ul>
189  
190<hr class="line">
191<ul>
192<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
193<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
194<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
195<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
196<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
197<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
198<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
199<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
200<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
201<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
202<li><a href="console.html" class="nav-console">Console</a></li>
203<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
204<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
205<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
206<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
207<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
208<li><a href="dns.html" class="nav-dns">DNS</a></li>
209<li><a href="domain.html" class="nav-domain">Domain</a></li>
210<li><a href="errors.html" class="nav-errors">Errors</a></li>
211<li><a href="events.html" class="nav-events">Events</a></li>
212<li><a href="fs.html" class="nav-fs">File system</a></li>
213<li><a href="globals.html" class="nav-globals">Globals</a></li>
214<li><a href="http.html" class="nav-http">HTTP</a></li>
215<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
216<li><a href="https.html" class="nav-https">HTTPS</a></li>
217<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
218<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
219<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
220<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
221<li><a href="module.html" class="nav-module active">Modules: <code>node:module</code> API</a></li>
222<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
223<li><a href="net.html" class="nav-net">Net</a></li>
224<li><a href="os.html" class="nav-os">OS</a></li>
225<li><a href="path.html" class="nav-path">Path</a></li>
226<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
227<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
228<li><a href="process.html" class="nav-process">Process</a></li>
229<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
230<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
231<li><a href="readline.html" class="nav-readline">Readline</a></li>
232<li><a href="repl.html" class="nav-repl">REPL</a></li>
233<li><a href="report.html" class="nav-report">Report</a></li>
234<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
235<li><a href="stream.html" class="nav-stream">Stream</a></li>
236<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
237<li><a href="test.html" class="nav-test">Test runner</a></li>
238<li><a href="timers.html" class="nav-timers">Timers</a></li>
239<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
240<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
241<li><a href="tty.html" class="nav-tty">TTY</a></li>
242<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
243<li><a href="url.html" class="nav-url">URL</a></li>
244<li><a href="util.html" class="nav-util">Utilities</a></li>
245<li><a href="v8.html" class="nav-v8">V8</a></li>
246<li><a href="vm.html" class="nav-vm">VM</a></li>
247<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
248<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
249<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
250<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
251<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
252</ul>
253<hr class="line">
254<ul>
255<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
256</ul></div>
257    </li>
258  
259            
260    <li class="picker-header">
261      <a href="#">
262        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
263        Other versions
264      </a>
265      <div class="picker"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v21.x/api/module.html">21.x</a></li>
266<li><a href="https://nodejs.org/docs/latest-v20.x/api/module.html">20.x <b>LTS</b></a></li>
267<li><a href="https://nodejs.org/docs/latest-v19.x/api/module.html">19.x</a></li>
268<li><a href="https://nodejs.org/docs/latest-v18.x/api/module.html">18.x <b>LTS</b></a></li>
269<li><a href="https://nodejs.org/docs/latest-v17.x/api/module.html">17.x</a></li>
270<li><a href="https://nodejs.org/docs/latest-v16.x/api/module.html">16.x</a></li>
271<li><a href="https://nodejs.org/docs/latest-v15.x/api/module.html">15.x</a></li>
272<li><a href="https://nodejs.org/docs/latest-v14.x/api/module.html">14.x</a></li>
273<li><a href="https://nodejs.org/docs/latest-v13.x/api/module.html">13.x</a></li>
274<li><a href="https://nodejs.org/docs/latest-v12.x/api/module.html">12.x</a></li></ol></div>
275    </li>
276  
277            <li class="picker-header">
278              <a href="#">
279                <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
280                Options
281              </a>
282        
283              <div class="picker">
284                <ul>
285                  <li>
286                    <a href="all.html">View on single page</a>
287                  </li>
288                  <li>
289                    <a href="module.json">View as JSON</a>
290                  </li>
291                  <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/main/doc/api/module.md">Edit on GitHub</a></li>    
292                </ul>
293              </div>
294            </li>
295          </ul>
296        </div>
297        <hr>
298      </header>
299
300      <details id="toc" open><summary>Table of contents</summary><ul>
301<li><a href="#modules-nodemodule-api">Modules: <code>node:module</code> API</a>
302<ul>
303<li><a href="#the-module-object">The <code>Module</code> object</a>
304<ul>
305<li><a href="#modulebuiltinmodules"><code>module.builtinModules</code></a></li>
306<li><a href="#modulecreaterequirefilename"><code>module.createRequire(filename)</code></a></li>
307<li><a href="#moduleisbuiltinmodulename"><code>module.isBuiltin(moduleName)</code></a></li>
308<li><span class="stability_1"><a href="#moduleregisterspecifier-parenturl-options"><code>module.register(specifier[, parentURL][, options])</code></a></span></li>
309<li><a href="#modulesyncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a></li>
310</ul>
311</li>
312<li><span class="stability_1"><a href="#customization-hooks">Customization Hooks</a></span>
313<ul>
314<li><a href="#enabling">Enabling</a></li>
315<li><a href="#chaining">Chaining</a></li>
316<li><a href="#communication-with-module-customization-hooks">Communication with module customization hooks</a></li>
317<li><a href="#hooks">Hooks</a>
318<ul>
319<li><span class="stability_1"><a href="#initialize"><code>initialize()</code></a></span></li>
320<li><span class="stability_1"><a href="#resolvespecifier-context-nextresolve"><code>resolve(specifier, context, nextResolve)</code></a></span></li>
321<li><span class="stability_1"><a href="#loadurl-context-nextload"><code>load(url, context, nextLoad)</code></a></span></li>
322<li><span class="stability_1"><a href="#globalpreload"><code>globalPreload()</code></a></span></li>
323</ul>
324</li>
325<li><a href="#examples">Examples</a>
326<ul>
327<li><a href="#import-from-https">Import from HTTPS</a></li>
328<li><a href="#transpilation">Transpilation</a></li>
329<li><a href="#import-maps">Import maps</a></li>
330</ul>
331</li>
332</ul>
333</li>
334<li><span class="stability_1"><a href="#source-map-v3-support">Source map v3 support</a></span>
335<ul>
336<li><a href="#modulefindsourcemappath"><code>module.findSourceMap(path)</code></a></li>
337<li><a href="#class-modulesourcemap">Class: <code>module.SourceMap</code></a>
338<ul>
339<li><a href="#new-sourcemappayload"><code>new SourceMap(payload)</code></a></li>
340<li><a href="#sourcemappayload"><code>sourceMap.payload</code></a></li>
341<li><a href="#sourcemapfindentrylineoffset-columnoffset"><code>sourceMap.findEntry(lineOffset, columnOffset)</code></a></li>
342<li><a href="#sourcemapfindoriginlinenumber-columnnumber"><code>sourceMap.findOrigin(lineNumber, columnNumber)</code></a></li>
343</ul>
344</li>
345</ul>
346</li>
347</ul>
348</li>
349</ul></details>
350
351      <div id="apicontent">
352        <h2>Modules: <code>node:module</code> API<span><a class="mark" href="#modules-nodemodule-api" id="modules-nodemodule-api">#</a></span><a aria-hidden="true" class="legacy" id="module_modules_node_module_api"></a></h2>
353
354<div class="api_metadata">
355<span>Added in: v0.3.7</span>
356</div>
357<section><h3>The <code>Module</code> object<span><a class="mark" href="#the-module-object" id="the-module-object">#</a></span><a aria-hidden="true" class="legacy" id="module_the_module_object"></a></h3>
358<ul>
359<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
360</ul>
361<p>Provides general utility methods when interacting with instances of
362<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
363via <code>import 'node:module'</code> or <code>require('node:module')</code>.</p>
364<h4><code>module.builtinModules</code><span><a class="mark" href="#modulebuiltinmodules" id="modulebuiltinmodules">#</a></span><a aria-hidden="true" class="legacy" id="module_module_builtinmodules"></a></h4>
365<div class="api_metadata">
366<span>Added in: v9.3.0, v8.10.0, v6.13.0</span>
367</div>
368<ul>
369<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
370</ul>
371<p>A list of the names of all modules provided by Node.js. Can be used to verify
372if a module is maintained by a third party or not.</p>
373<p><code>module</code> in this context isn't the same object that's provided
374by the <a href="modules.html#the-module-wrapper">module wrapper</a>. To access it, require the <code>Module</code> module:</p>
375
376<pre class="with-26-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// module.mjs</span>
377<span class="hljs-comment">// In an ECMAScript module</span>
378<span class="hljs-keyword">import</span> { builtinModules <span class="hljs-keyword">as</span> builtin } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;</code><code class="language-js cjs"><span class="hljs-comment">// module.cjs</span>
379<span class="hljs-comment">// In a CommonJS module</span>
380<span class="hljs-keyword">const</span> builtin = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>).<span class="hljs-property">builtinModules</span>;</code><button class="copy-button">copy</button></pre>
381<h4><code>module.createRequire(filename)</code><span><a class="mark" href="#modulecreaterequirefilename" id="modulecreaterequirefilename">#</a></span><a aria-hidden="true" class="legacy" id="module_module_createrequire_filename"></a></h4>
382<div class="api_metadata">
383<span>Added in: v12.2.0</span>
384</div>
385<ul>
386<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="url.html#the-whatwg-url-api" class="type">&#x3C;URL></a> Filename to be used to construct the require
387function. Must be a file URL object, file URL string, or absolute path
388string.</li>
389<li>Returns: <a href="modules.html#requireid" class="type">&#x3C;require></a> Require function</li>
390</ul>
391<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { createRequire } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
392<span class="hljs-keyword">const</span> <span class="hljs-built_in">require</span> = <span class="hljs-title function_">createRequire</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
393
394<span class="hljs-comment">// sibling-module.js is a CommonJS module.</span>
395<span class="hljs-keyword">const</span> siblingModule = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./sibling-module'</span>);</code> <button class="copy-button">copy</button></pre>
396<h4><code>module.isBuiltin(moduleName)</code><span><a class="mark" href="#moduleisbuiltinmodulename" id="moduleisbuiltinmodulename">#</a></span><a aria-hidden="true" class="legacy" id="module_module_isbuiltin_modulename"></a></h4>
397<div class="api_metadata">
398<span>Added in: v18.6.0</span>
399</div>
400<ul>
401<li><code>moduleName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> name of the module</li>
402<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> returns true if the module is builtin else returns false</li>
403</ul>
404<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { isBuiltin } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
405<span class="hljs-title function_">isBuiltin</span>(<span class="hljs-string">'node:fs'</span>); <span class="hljs-comment">// true</span>
406<span class="hljs-title function_">isBuiltin</span>(<span class="hljs-string">'fs'</span>); <span class="hljs-comment">// true</span>
407<span class="hljs-title function_">isBuiltin</span>(<span class="hljs-string">'wss'</span>); <span class="hljs-comment">// false</span></code> <button class="copy-button">copy</button></pre>
408<h4><code>module.register(specifier[, parentURL][, options])</code><span><a class="mark" href="#moduleregisterspecifier-parenturl-options" id="moduleregisterspecifier-parenturl-options">#</a></span><a aria-hidden="true" class="legacy" id="module_module_register_specifier_parenturl_options"></a></h4>
409<div class="api_metadata">
410<details class="changelog"><summary>History</summary>
411<table>
412<tbody><tr><th>Version</th><th>Changes</th></tr>
413<tr><td>v18.19.0</td>
414<td><p>Add support for WHATWG URL instances.</p></td></tr>
415<tr><td>v18.19.0</td>
416<td><p><span>Added in: v18.19.0</span></p></td></tr>
417</tbody></table>
418</details>
419</div>
420<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a>.1 - Active development</div><p></p>
421<ul>
422<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="url.html#the-whatwg-url-api" class="type">&#x3C;URL></a> Customization hooks to be registered; this should be
423the same string that would be passed to <code>import()</code>, except that if it is
424relative, it is resolved relative to <code>parentURL</code>.</li>
425<li><code>parentURL</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="url.html#the-whatwg-url-api" class="type">&#x3C;URL></a> If you want to resolve <code>specifier</code> relative to a base
426URL, such as <code>import.meta.url</code>, you can pass that URL here. <strong>Default:</strong>
427<code>'data:'</code></li>
428<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
429<ul>
430<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Any arbitrary, cloneable JavaScript value to pass into the
431<a href="#initialize"><code>initialize</code></a> hook.</li>
432<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a> <a href="worker_threads.html#portpostmessagevalue-transferlist">transferrable objects</a> to be passed into the
433<code>initialize</code> hook.</li>
434</ul>
435</li>
436</ul>
437<p>Register a module that exports <a href="#customization-hooks">hooks</a> that customize Node.js module
438resolution and loading behavior. See <a href="#customization-hooks">Customization hooks</a>.</p>
439<h4><code>module.syncBuiltinESMExports()</code><span><a class="mark" href="#modulesyncbuiltinesmexports" id="modulesyncbuiltinesmexports">#</a></span><a aria-hidden="true" class="legacy" id="module_module_syncbuiltinesmexports"></a></h4>
440<div class="api_metadata">
441<span>Added in: v12.12.0</span>
442</div>
443<p>The <code>module.syncBuiltinESMExports()</code> method updates all the live bindings for
444builtin <a href="esm.html">ES Modules</a> to match the properties of the <a href="modules.html">CommonJS</a> exports. It
445does not add or remove exported names from the <a href="esm.html">ES Modules</a>.</p>
446<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
447<span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
448<span class="hljs-keyword">const</span> { syncBuiltinESMExports } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
449
450fs.<span class="hljs-property">readFile</span> = newAPI;
451
452<span class="hljs-keyword">delete</span> fs.<span class="hljs-property">readFileSync</span>;
453
454<span class="hljs-keyword">function</span> <span class="hljs-title function_">newAPI</span>(<span class="hljs-params"></span>) {
455  <span class="hljs-comment">// ...</span>
456}
457
458fs.<span class="hljs-property">newAPI</span> = newAPI;
459
460<span class="hljs-title function_">syncBuiltinESMExports</span>();
461
462<span class="hljs-keyword">import</span>(<span class="hljs-string">'node:fs'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">esmFS</span>) =></span> {
463  <span class="hljs-comment">// It syncs the existing readFile property with the new value</span>
464  assert.<span class="hljs-title function_">strictEqual</span>(esmFS.<span class="hljs-property">readFile</span>, newAPI);
465  <span class="hljs-comment">// readFileSync has been deleted from the required fs</span>
466  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-string">'readFileSync'</span> <span class="hljs-keyword">in</span> fs, <span class="hljs-literal">false</span>);
467  <span class="hljs-comment">// syncBuiltinESMExports() does not remove readFileSync from esmFS</span>
468  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-string">'readFileSync'</span> <span class="hljs-keyword">in</span> esmFS, <span class="hljs-literal">true</span>);
469  <span class="hljs-comment">// syncBuiltinESMExports() does not add names</span>
470  assert.<span class="hljs-title function_">strictEqual</span>(esmFS.<span class="hljs-property">newAPI</span>, <span class="hljs-literal">undefined</span>);
471});</code> <button class="copy-button">copy</button></pre>
472<p><i id="module_customization_hooks"></i></p>
473</section><section><h3>Customization Hooks<span><a class="mark" href="#customization-hooks" id="customization-hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_customization_hooks"></a></h3>
474<div class="api_metadata">
475<details class="changelog"><summary>History</summary>
476<table>
477<tbody><tr><th>Version</th><th>Changes</th></tr>
478<tr><td>v18.19.0</td>
479<td><p>Added <code>initialize</code> hook to replace <code>globalPreload</code>.</p></td></tr>
480<tr><td>v18.6.0, v16.17.0</td>
481<td><p>Add support for chaining loaders.</p></td></tr>
482<tr><td>v16.12.0</td>
483<td><p>Removed <code>getFormat</code>, <code>getSource</code>, <code>transformSource</code>, and <code>globalPreload</code>; added <code>load</code> hook and <code>getGlobalPreload</code> hook.</p></td></tr>
484<tr><td>v8.8.0</td>
485<td><p><span>Added in: v8.8.0</span></p></td></tr>
486</tbody></table>
487</details>
488</div>
489<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a>.1 - Active development</div><p></p>
490
491<p><i id="enabling_module_customization_hooks"></i></p>
492<h4>Enabling<span><a class="mark" href="#enabling" id="enabling">#</a></span><a aria-hidden="true" class="legacy" id="module_enabling"></a></h4>
493<p>Module resolution and loading can be customized by registering a file which
494exports a set of hooks. This can be done using the <a href="#moduleregisterspecifier-parenturl-options"><code>register</code></a> method
495from <code>node:module</code>, which you can run before your application code by
496using the <code>--import</code> flag:</p>
497<pre><code class="language-bash">node --import ./register-hooks.js ./my-app.js</code> <button class="copy-button">copy</button></pre>
498
499<pre class="with-44-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// register-hooks.js</span>
500<span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
501
502<span class="hljs-title function_">register</span>(<span class="hljs-string">'./hooks.mjs'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);</code><code class="language-js cjs"><span class="hljs-comment">// register-hooks.js</span>
503<span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
504<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
505
506<span class="hljs-title function_">register</span>(<span class="hljs-string">'./hooks.mjs'</span>, <span class="hljs-title function_">pathToFileURL</span>(__filename));</code><button class="copy-button">copy</button></pre>
507<p>The file passed to <code>--import</code> can also be an export from a dependency:</p>
508<pre><code class="language-bash">node --import some-package/register ./my-app.js</code> <button class="copy-button">copy</button></pre>
509<p>Where <code>some-package</code> has an <a href="packages.html#exports"><code>"exports"</code></a> field defining the <code>/register</code>
510export to map to a file that calls <code>register()</code>, like the following <code>register-hooks.js</code>
511example.</p>
512<p>Using <code>--import</code> ensures that the hooks are registered before any application
513files are imported, including the entry point of the application. Alternatively,
514<code>register</code> can be called from the entry point, but dynamic <code>import()</code> must be
515used for any code that should be run after the hooks are registered:</p>
516
517<pre class="with-46-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
518
519<span class="hljs-title function_">register</span>(<span class="hljs-string">'http-to-https'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
520
521<span class="hljs-comment">// Because this is a dynamic `import()`, the `http-to-https` hooks will run</span>
522<span class="hljs-comment">// to handle `./my-app.js` and any other files it imports or requires.</span>
523<span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.js'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
524<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
525
526<span class="hljs-title function_">register</span>(<span class="hljs-string">'http-to-https'</span>, <span class="hljs-title function_">pathToFileURL</span>(__filename));
527
528<span class="hljs-comment">// Because this is a dynamic `import()`, the `http-to-https` hooks will run</span>
529<span class="hljs-comment">// to handle `./my-app.js` and any other files it imports or requires.</span>
530<span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.js'</span>);</code><button class="copy-button">copy</button></pre>
531<p>In this example, we are registering the <code>http-to-https</code> hooks, but they will
532only be available for subsequently imported modules—in this case, <code>my-app.js</code>
533and anything it references via <code>import</code> (and optionally <code>require</code>). If the
534<code>import('./my-app.js')</code> had instead been a static <code>import './my-app.js'</code>, the
535app would have <em>already</em> been loaded <strong>before</strong> the <code>http-to-https</code> hooks were
536registered. This due to the ES modules specification, where static imports are
537evaluated from the leaves of the tree first, then back to the trunk. There can
538be static imports <em>within</em> <code>my-app.js</code>, which will not be evaluated until
539<code>my-app.js</code> is dynamically imported.</p>
540<p><code>my-app.js</code> can also be CommonJS. Customization hooks will run for any
541modules that it references via <code>import</code> (and optionally <code>require</code>).</p>
542<p>Finally, if all you want to do is register hooks before your app runs and you
543don't want to create a separate file for that purpose, you can pass a <code>data:</code>
544URL to <code>--import</code>:</p>
545<pre><code class="language-bash">node --import <span class="hljs-string">'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register("http-to-https", pathToFileURL("./"));'</span> ./my-app.js</code> <button class="copy-button">copy</button></pre>
546<h4>Chaining<span><a class="mark" href="#chaining" id="chaining">#</a></span><a aria-hidden="true" class="legacy" id="module_chaining"></a></h4>
547<p>It's possible to call <code>register</code> more than once:</p>
548
549<pre class="with-44-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// entrypoint.mjs</span>
550<span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
551
552<span class="hljs-title function_">register</span>(<span class="hljs-string">'./first.mjs'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
553<span class="hljs-title function_">register</span>(<span class="hljs-string">'./second.mjs'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
554<span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.mjs'</span>);</code><code class="language-js cjs"><span class="hljs-comment">// entrypoint.cjs</span>
555<span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
556<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
557
558<span class="hljs-keyword">const</span> parentURL = <span class="hljs-title function_">pathToFileURL</span>(__filename);
559<span class="hljs-title function_">register</span>(<span class="hljs-string">'./first.mjs'</span>, parentURL);
560<span class="hljs-title function_">register</span>(<span class="hljs-string">'./second.mjs'</span>, parentURL);
561<span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.mjs'</span>);</code><button class="copy-button">copy</button></pre>
562<p>In this example, the registered hooks will form chains. If both <code>first.mjs</code> and
563<code>second.mjs</code> define a <code>resolve</code> hook, both will be called, in the order they
564were registered. The same applies to all the other hooks.</p>
565<p>The registered hooks also affect <code>register</code> itself. In this example,
566<code>second.mjs</code> will be resolved and loaded per the hooks registered by
567<code>first.mjs</code>. This allows for things like writing hooks in non-JavaScript
568languages, so long as an earlier registered loader is one that transpiles into
569JavaScript.</p>
570<p>The <code>register</code> method cannot be called from within the module that defines the
571hooks.</p>
572<h4>Communication with module customization hooks<span><a class="mark" href="#communication-with-module-customization-hooks" id="communication-with-module-customization-hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_communication_with_module_customization_hooks"></a></h4>
573<p>Module customization hooks run on a dedicated thread, separate from the main
574thread that runs application code. This means mutating global variables won't
575affect the other thread(s), and message channels must be used to communicate
576between the threads.</p>
577<p>The <code>register</code> method can be used to pass data to an <a href="#initialize"><code>initialize</code></a> hook. The
578data passed to the hook may include transferrable objects like ports.</p>
579
580<pre class="with-53-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
581<span class="hljs-keyword">import</span> { <span class="hljs-title class_">MessageChannel</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;
582
583<span class="hljs-comment">// This example demonstrates how a message channel can be used to</span>
584<span class="hljs-comment">// communicate with the hooks, by sending `port2` to the hooks.</span>
585<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
586
587port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
588  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(msg);
589});
590
591<span class="hljs-title function_">register</span>(<span class="hljs-string">'./my-hooks.mjs'</span>, {
592  <span class="hljs-attr">parentURL</span>: <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>,
593  <span class="hljs-attr">data</span>: { <span class="hljs-attr">number</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">port</span>: port2 },
594  <span class="hljs-attr">transferList</span>: [port2],
595});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
596<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
597<span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
598
599<span class="hljs-comment">// This example showcases how a message channel can be used to</span>
600<span class="hljs-comment">// communicate with the hooks, by sending `port2` to the hooks.</span>
601<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
602
603port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
604  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(msg);
605});
606
607<span class="hljs-title function_">register</span>(<span class="hljs-string">'./my-hooks.mjs'</span>, {
608  <span class="hljs-attr">parentURL</span>: <span class="hljs-title function_">pathToFileURL</span>(__filename),
609  <span class="hljs-attr">data</span>: { <span class="hljs-attr">number</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">port</span>: port2 },
610  <span class="hljs-attr">transferList</span>: [port2],
611});</code><button class="copy-button">copy</button></pre>
612<h4>Hooks<span><a class="mark" href="#hooks" id="hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_hooks"></a></h4>
613<p>The <a href="#moduleregisterspecifier-parenturl-options"><code>register</code></a> method can be used to register a module that exports a set of
614hooks. The hooks are functions that are called by Node.js to customize the
615module resolution and loading process. The exported functions must have specific
616names and signatures, and they must be exported as named exports.</p>
617<pre><code class="language-js mjs"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">initialize</span>(<span class="hljs-params">{ number, port }</span>) {
618  <span class="hljs-comment">// Receives data from `register`.</span>
619}
620
621<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) {
622  <span class="hljs-comment">// Take an `import` or `require` specifier and resolve it to a URL.</span>
623}
624
625<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
626  <span class="hljs-comment">// Take a resolved URL and return the source code to be evaluated.</span>
627}</code> <button class="copy-button">copy</button></pre>
628<p>Hooks are part of a chain, even if that chain consists of only one custom
629(user-provided) hook and the default hook, which is always present. Hook
630functions nest: each one must always return a plain object, and chaining happens
631as a result of each function calling <code>next&#x3C;hookName>()</code>, which is a reference to
632the subsequent loader's hook.</p>
633<p>A hook that returns a value lacking a required property triggers an exception. A
634hook that returns without calling <code>next&#x3C;hookName>()</code> <em>and</em> without returning
635<code>shortCircuit: true</code> also triggers an exception. These errors are to help
636prevent unintentional breaks in the chain. Return <code>shortCircuit: true</code> from a
637hook to signal that the chain is intentionally ending at your hook.</p>
638<p>Hooks are run in a separate thread, isolated from the main thread where
639application code runs. That means it is a different <a href="https://tc39.es/ecma262/#realm">realm</a>. The hooks thread
640may be terminated by the main thread at any time, so do not depend on
641asynchronous operations (like <code>console.log</code>) to complete.</p>
642<h5><code>initialize()</code><span><a class="mark" href="#initialize" id="initialize">#</a></span><a aria-hidden="true" class="legacy" id="module_initialize"></a></h5>
643<div class="api_metadata">
644<span>Added in: v18.19.0</span>
645</div>
646<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a>.1 - Active development</div><p></p>
647<ul>
648<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The data from <code>register(loader, import.meta.url, { data })</code>.</li>
649</ul>
650<p>The <code>initialize</code> hook provides a way to define a custom function that runs in
651the hooks thread when the hooks module is initialized. Initialization happens
652when the hooks module is registered via <a href="#moduleregisterspecifier-parenturl-options"><code>register</code></a>.</p>
653<p>This hook can receive data from a <a href="#moduleregisterspecifier-parenturl-options"><code>register</code></a> invocation, including
654ports and other transferrable objects. The return value of <code>initialize</code> can be a
655<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a>, in which case it will be awaited before the main application thread
656execution resumes.</p>
657<p>Module customization code:</p>
658<pre><code class="language-js mjs"><span class="hljs-comment">// path-to-my-hooks.js</span>
659
660<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">initialize</span>(<span class="hljs-params">{ number, port }</span>) {
661  port.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">`increment: <span class="hljs-subst">${number + <span class="hljs-number">1</span>}</span>`</span>);
662}</code> <button class="copy-button">copy</button></pre>
663<p>Caller code:</p>
664
665<pre class="with-44-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
666<span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
667<span class="hljs-keyword">import</span> { <span class="hljs-title class_">MessageChannel</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;
668
669<span class="hljs-comment">// This example showcases how a message channel can be used to communicate</span>
670<span class="hljs-comment">// between the main (application) thread and the hooks running on the hooks</span>
671<span class="hljs-comment">// thread, by sending `port2` to the `initialize` hook.</span>
672<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
673
674port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
675  assert.<span class="hljs-title function_">strictEqual</span>(msg, <span class="hljs-string">'increment: 2'</span>);
676});
677
678<span class="hljs-title function_">register</span>(<span class="hljs-string">'./path-to-my-hooks.js'</span>, {
679  <span class="hljs-attr">parentURL</span>: <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>,
680  <span class="hljs-attr">data</span>: { <span class="hljs-attr">number</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">port</span>: port2 },
681  <span class="hljs-attr">transferList</span>: [port2],
682});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
683<span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
684<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
685<span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
686
687<span class="hljs-comment">// This example showcases how a message channel can be used to communicate</span>
688<span class="hljs-comment">// between the main (application) thread and the hooks running on the hooks</span>
689<span class="hljs-comment">// thread, by sending `port2` to the `initialize` hook.</span>
690<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
691
692port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
693  assert.<span class="hljs-title function_">strictEqual</span>(msg, <span class="hljs-string">'increment: 2'</span>);
694});
695
696<span class="hljs-title function_">register</span>(<span class="hljs-string">'./path-to-my-hooks.js'</span>, {
697  <span class="hljs-attr">parentURL</span>: <span class="hljs-title function_">pathToFileURL</span>(__filename),
698  <span class="hljs-attr">data</span>: { <span class="hljs-attr">number</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">port</span>: port2 },
699  <span class="hljs-attr">transferList</span>: [port2],
700});</code><button class="copy-button">copy</button></pre>
701<h5><code>resolve(specifier, context, nextResolve)</code><span><a class="mark" href="#resolvespecifier-context-nextresolve" id="resolvespecifier-context-nextresolve">#</a></span><a aria-hidden="true" class="legacy" id="module_resolve_specifier_context_nextresolve"></a></h5>
702<div class="api_metadata">
703<details class="changelog"><summary>History</summary>
704<table>
705<tbody><tr><th>Version</th><th>Changes</th></tr>
706<tr><td>v18.19.0</td>
707<td><p>The property <code>context.importAssertions</code> is replaced with <code>context.importAttributes</code>. Using the old name is still supported and will emit an experimental warning.</p></td></tr>
708<tr><td>v18.6.0, v16.17.0</td>
709<td><p>Add support for chaining resolve hooks. Each hook must either call <code>nextResolve()</code> or include a <code>shortCircuit</code> property set to <code>true</code> in its return.</p></td></tr>
710<tr><td>v17.1.0, v16.14.0</td>
711<td><p>Add support for import assertions.</p></td></tr>
712</tbody></table>
713</details>
714</div>
715<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
716<ul>
717<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
718<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
719<ul>
720<li><code>conditions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> Export conditions of the relevant <code>package.json</code></li>
721<li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An object whose key-value pairs represent the
722attributes for the module to import</li>
723<li><code>parentURL</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The module importing this one, or undefined
724if this is the Node.js entry point</li>
725</ul>
726</li>
727<li><code>nextResolve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The subsequent <code>resolve</code> hook in the chain, or the
728Node.js default <code>resolve</code> hook after the last user-supplied <code>resolve</code> hook
729<ul>
730<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
731<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
732</ul>
733</li>
734<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a>
735<ul>
736<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> A hint to the load hook (it might be
737ignored)
738<code>'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'</code></li>
739<li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The import attributes to use when
740caching the module (optional; if excluded the input will be used)</li>
741<li><code>shortCircuit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> A signal that this hook intends to
742terminate the chain of <code>resolve</code> hooks. <strong>Default:</strong> <code>false</code></li>
743<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The absolute URL to which this input resolves</li>
744</ul>
745</li>
746</ul>
747<blockquote>
748<p><strong>Warning</strong> Despite support for returning promises and async functions, calls
749to <code>resolve</code> may block the main thread which can impact performance.</p>
750</blockquote>
751<p>The <code>resolve</code> hook chain is responsible for telling Node.js where to find and
752how to cache a given <code>import</code> statement or expression, or <code>require</code> call. It can
753optionally return a format (such as <code>'module'</code>) as a hint to the <code>load</code> hook. If
754a format is specified, the <code>load</code> hook is ultimately responsible for providing
755the final <code>format</code> value (and it is free to ignore the hint provided by
756<code>resolve</code>); if <code>resolve</code> provides a <code>format</code>, a custom <code>load</code> hook is required
757even if only to pass the value to the Node.js default <code>load</code> hook.</p>
758<p>Import type attributes are part of the cache key for saving loaded modules into
759the internal module cache. The <code>resolve</code> hook is responsible for returning an
760<code>importAttributes</code> object if the module should be cached with different
761attributes than were present in the source code.</p>
762<p>The <code>conditions</code> property in <code>context</code> is an array of conditions for
763<a href="packages.html#conditional-exports">package exports conditions</a> that apply to this resolution
764request. They can be used for looking up conditional mappings elsewhere or to
765modify the list when calling the default resolution logic.</p>
766<p>The current <a href="packages.html#conditional-exports">package exports conditions</a> are always in
767the <code>context.conditions</code> array passed into the hook. To guarantee <em>default
768Node.js module specifier resolution behavior</em> when calling <code>defaultResolve</code>, the
769<code>context.conditions</code> array passed to it <em>must</em> include <em>all</em> elements of the
770<code>context.conditions</code> array originally passed into the <code>resolve</code> hook.</p>
771<pre><code class="language-js mjs"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) {
772  <span class="hljs-keyword">const</span> { parentURL = <span class="hljs-literal">null</span> } = context;
773
774  <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() > <span class="hljs-number">0.5</span>) { <span class="hljs-comment">// Some condition.</span>
775    <span class="hljs-comment">// For some or all specifiers, do some custom logic for resolving.</span>
776    <span class="hljs-comment">// Always return an object of the form {url: &#x3C;string>}.</span>
777    <span class="hljs-keyword">return</span> {
778      <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
779      <span class="hljs-attr">url</span>: parentURL ?
780        <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(specifier, parentURL).<span class="hljs-property">href</span> :
781        <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(specifier).<span class="hljs-property">href</span>,
782    };
783  }
784
785  <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() &#x3C; <span class="hljs-number">0.5</span>) { <span class="hljs-comment">// Another condition.</span>
786    <span class="hljs-comment">// When calling `defaultResolve`, the arguments can be modified. In this</span>
787    <span class="hljs-comment">// case it's adding another value for matching conditional exports.</span>
788    <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier, {
789      ...context,
790      <span class="hljs-attr">conditions</span>: [...context.<span class="hljs-property">conditions</span>, <span class="hljs-string">'another-condition'</span>],
791    });
792  }
793
794  <span class="hljs-comment">// Defer to the next hook in the chain, which would be the</span>
795  <span class="hljs-comment">// Node.js default resolve if this is the last user-specified loader.</span>
796  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier);
797}</code> <button class="copy-button">copy</button></pre>
798<h5><code>load(url, context, nextLoad)</code><span><a class="mark" href="#loadurl-context-nextload" id="loadurl-context-nextload">#</a></span><a aria-hidden="true" class="legacy" id="module_load_url_context_nextload"></a></h5>
799<div class="api_metadata">
800<details class="changelog"><summary>History</summary>
801<table>
802<tbody><tr><th>Version</th><th>Changes</th></tr>
803<tr><td>v18.6.0, v16.17.0</td>
804<td><p>Add support for chaining load hooks. Each hook must either call <code>nextLoad()</code> or include a <code>shortCircuit</code> property set to <code>true</code> in its return.</p></td></tr>
805</tbody></table>
806</details>
807</div>
808<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
809<ul>
810<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The URL returned by the <code>resolve</code> chain</li>
811<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
812<ul>
813<li><code>conditions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> Export conditions of the relevant <code>package.json</code></li>
814<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The format optionally supplied by the
815<code>resolve</code> hook chain</li>
816<li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
817</ul>
818</li>
819<li><code>nextLoad</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The subsequent <code>load</code> hook in the chain, or the
820Node.js default <code>load</code> hook after the last user-supplied <code>load</code> hook
821<ul>
822<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
823<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
824</ul>
825</li>
826<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
827<ul>
828<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
829<li><code>shortCircuit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> A signal that this hook intends to
830terminate the chain of <code>resolve</code> hooks. <strong>Default:</strong> <code>false</code></li>
831<li><code>source</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> The source for Node.js to evaluate</li>
832</ul>
833</li>
834</ul>
835<p>The <code>load</code> hook provides a way to define a custom method of determining how a
836URL should be interpreted, retrieved, and parsed. It is also in charge of
837validating the import assertion.</p>
838<p>The final value of <code>format</code> must be one of the following:</p>
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874<table><thead><tr><th><code>format</code></th><th>Description</th><th>Acceptable types for <code>source</code> returned by <code>load</code></th></tr></thead><tbody><tr><td><code>'builtin'</code></td><td>Load a Node.js builtin module</td><td>Not applicable</td></tr><tr><td><code>'commonjs'</code></td><td>Load a Node.js CommonJS module</td><td>Not applicable</td></tr><tr><td><code>'json'</code></td><td>Load a JSON file</td><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></tr><tr><td><code>'module'</code></td><td>Load an ES module</td><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></tr><tr><td><code>'wasm'</code></td><td>Load a WebAssembly module</td><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></tr></tbody></table>
875<p>The value of <code>source</code> is ignored for type <code>'builtin'</code> because currently it is
876not possible to replace the value of a Node.js builtin (core) module. The value
877of <code>source</code> is ignored for type <code>'commonjs'</code> because the CommonJS module loader
878does not provide a mechanism for the ES module loader to override the
879<a href="esm.html#commonjs-namespaces">CommonJS module return value</a>. This limitation
880might be overcome in the future.</p>
881<blockquote>
882<p><strong>Warning</strong>: The ESM <code>load</code> hook and namespaced exports from CommonJS modules
883are incompatible. Attempting to use them together will result in an empty
884object from the import. This may be addressed in the future.</p>
885</blockquote>
886<blockquote>
887<p>These types all correspond to classes defined in ECMAScript.</p>
888</blockquote>
889<ul>
890<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>
891<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>
892</ul>
893<p>If the source value of a text-based format (i.e., <code>'json'</code>, <code>'module'</code>)
894is not a string, it is converted to a string using <a href="util.html#class-utiltextdecoder"><code>util.TextDecoder</code></a>.</p>
895<p>The <code>load</code> hook provides a way to define a custom method for retrieving the
896source code of a resolved URL. This would allow a loader to potentially avoid
897reading files from disk. It could also be used to map an unrecognized format to
898a supported one, for example <code>yaml</code> to <code>module</code>.</p>
899<pre><code class="language-js mjs"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
900  <span class="hljs-keyword">const</span> { format } = context;
901
902  <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() > <span class="hljs-number">0.5</span>) { <span class="hljs-comment">// Some condition</span>
903    <span class="hljs-comment">/*
904      For some or all URLs, do some custom logic for retrieving the source.
905      Always return an object of the form {
906        format: &#x3C;string>,
907        source: &#x3C;string|buffer>,
908      }.
909    */</span>
910    <span class="hljs-keyword">return</span> {
911      format,
912      <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
913      <span class="hljs-attr">source</span>: <span class="hljs-string">'...'</span>,
914    };
915  }
916
917  <span class="hljs-comment">// Defer to the next hook in the chain.</span>
918  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url);
919}</code> <button class="copy-button">copy</button></pre>
920<p>In a more advanced scenario, this can also be used to transform an unsupported
921source to a supported one (see <a href="#examples">Examples</a> below).</p>
922<h5><code>globalPreload()</code><span><a class="mark" href="#globalpreload" id="globalpreload">#</a></span><a aria-hidden="true" class="legacy" id="module_globalpreload"></a></h5>
923<div class="api_metadata">
924<details class="changelog"><summary>History</summary>
925<table>
926<tbody><tr><th>Version</th><th>Changes</th></tr>
927<tr><td>v18.6.0, v16.17.0</td>
928<td><p>Add support for chaining globalPreload hooks.</p></td></tr>
929</tbody></table>
930</details>
931</div>
932<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a>.0 - Early development</div><p></p>
933<blockquote>
934<p><strong>Warning:</strong> This hook will be removed in a future version. Use
935<a href="#initialize"><code>initialize</code></a> instead. When a hooks module has an <code>initialize</code> export,
936<code>globalPreload</code> will be ignored.</p>
937</blockquote>
938<ul>
939<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Information to assist the preload code
940<ul>
941<li><code>port</code> <a href="worker_threads.html#class-messageport" class="type">&#x3C;MessagePort></a></li>
942</ul>
943</li>
944<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Code to run before application startup</li>
945</ul>
946<p>Sometimes it might be necessary to run some code inside of the same global
947scope that the application runs in. This hook allows the return of a string
948that is run as a sloppy-mode script on startup.</p>
949<p>Similar to how CommonJS wrappers work, the code runs in an implicit function
950scope. The only argument is a <code>require</code>-like function that can be used to load
951builtins like "fs": <code>getBuiltin(request: string)</code>.</p>
952<p>If the code needs more advanced <code>require</code> features, it has to construct
953its own <code>require</code> using  <code>module.createRequire()</code>.</p>
954<pre><code class="language-js mjs"><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">globalPreload</span>(<span class="hljs-params">context</span>) {
955  <span class="hljs-keyword">return</span> <span class="hljs-string">`\
956globalThis.someInjectedProperty = 42;
957console.log('I just set some globals!');
958
959const { createRequire } = getBuiltin('module');
960const { cwd } = getBuiltin('process');
961
962const require = createRequire(cwd() + '/&#x3C;preload>');
963// [...]
964`</span>;
965}</code> <button class="copy-button">copy</button></pre>
966<p>Another argument is provided to the preload code: <code>port</code>. This is available as a
967parameter to the hook and inside of the source text returned by the hook. This
968functionality has been moved to the <code>initialize</code> hook.</p>
969<p>Care must be taken in order to properly call <a href="worker_threads.html#portref"><code>port.ref()</code></a> and
970<a href="worker_threads.html#portunref"><code>port.unref()</code></a> to prevent a process from being in a state where it won't
971close normally.</p>
972<pre><code class="language-js mjs"><span class="hljs-comment">/**
973 * This example has the application context send a message to the hook
974 * and sends the message back to the application context
975 */</span>
976<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">globalPreload</span>(<span class="hljs-params">{ port }</span>) {
977  port.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
978    port.<span class="hljs-title function_">postMessage</span>(msg);
979  });
980  <span class="hljs-keyword">return</span> <span class="hljs-string">`\
981    port.postMessage('console.log("I went to the hook and back");');
982    port.on('message', (msg) => {
983      eval(msg);
984    });
985  `</span>;
986}</code> <button class="copy-button">copy</button></pre>
987<h4>Examples<span><a class="mark" href="#examples" id="examples">#</a></span><a aria-hidden="true" class="legacy" id="module_examples"></a></h4>
988<p>The various module customization hooks can be used together to accomplish
989wide-ranging customizations of the Node.js code loading and evaluation
990behaviors.</p>
991<h5>Import from HTTPS<span><a class="mark" href="#import-from-https" id="import-from-https">#</a></span><a aria-hidden="true" class="legacy" id="module_import_from_https"></a></h5>
992<p>In current Node.js, specifiers starting with <code>https://</code> are experimental (see
993<a href="esm.html#https-and-http-imports">HTTPS and HTTP imports</a>).</p>
994<p>The hook below registers hooks to enable rudimentary support for such
995specifiers. While this may seem like a significant improvement to Node.js core
996functionality, there are substantial downsides to actually using these hooks:
997performance is much slower than loading files from disk, there is no caching,
998and there is no security.</p>
999<pre><code class="language-js mjs"><span class="hljs-comment">// https-hooks.mjs</span>
1000<span class="hljs-keyword">import</span> { get } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:https'</span>;
1001
1002<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
1003  <span class="hljs-comment">// For JavaScript to be loaded over the network, we need to fetch and</span>
1004  <span class="hljs-comment">// return it.</span>
1005  <span class="hljs-keyword">if</span> (url.<span class="hljs-title function_">startsWith</span>(<span class="hljs-string">'https://'</span>)) {
1006    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
1007      <span class="hljs-title function_">get</span>(url, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
1008        <span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>;
1009        res.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
1010        res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> data += chunk);
1011        res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> <span class="hljs-title function_">resolve</span>({
1012          <span class="hljs-comment">// This example assumes all network-provided JavaScript is ES module</span>
1013          <span class="hljs-comment">// code.</span>
1014          <span class="hljs-attr">format</span>: <span class="hljs-string">'module'</span>,
1015          <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
1016          <span class="hljs-attr">source</span>: data,
1017        }));
1018      }).<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> <span class="hljs-title function_">reject</span>(err));
1019    });
1020  }
1021
1022  <span class="hljs-comment">// Let Node.js handle all other URLs.</span>
1023  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url);
1024}</code> <button class="copy-button">copy</button></pre>
1025<pre><code class="language-js mjs"><span class="hljs-comment">// main.mjs</span>
1026<span class="hljs-keyword">import</span> { <span class="hljs-variable constant_">VERSION</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'https://coffeescript.org/browser-compiler-modern/coffeescript.js'</span>;
1027
1028<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-variable constant_">VERSION</span>);</code> <button class="copy-button">copy</button></pre>
1029<p>With the preceding hooks module, running
1030<code>node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./https-hooks.mjs"));' ./main.mjs</code>
1031prints the current version of CoffeeScript per the module at the URL in
1032<code>main.mjs</code>.</p>
1033<h5>Transpilation<span><a class="mark" href="#transpilation" id="transpilation">#</a></span><a aria-hidden="true" class="legacy" id="module_transpilation"></a></h5>
1034<p>Sources that are in formats Node.js doesn't understand can be converted into
1035JavaScript using the <a href="#loadurl-context-nextload"><code>load</code> hook</a>.</p>
1036<p>This is less performant than transpiling source files before running Node.js;
1037transpiler hooks should only be used for development and testing purposes.</p>
1038<pre><code class="language-js mjs"><span class="hljs-comment">// coffeescript-hooks.mjs</span>
1039<span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
1040<span class="hljs-keyword">import</span> { dirname, extname, resolve <span class="hljs-keyword">as</span> resolvePath } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;
1041<span class="hljs-keyword">import</span> { cwd } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
1042<span class="hljs-keyword">import</span> { fileURLToPath, pathToFileURL } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
1043<span class="hljs-keyword">import</span> coffeescript <span class="hljs-keyword">from</span> <span class="hljs-string">'coffeescript'</span>;
1044
1045<span class="hljs-keyword">const</span> extensionsRegex = <span class="hljs-regexp">/\.(coffee|litcoffee|coffee\.md)$/</span>;
1046
1047<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
1048  <span class="hljs-keyword">if</span> (extensionsRegex.<span class="hljs-title function_">test</span>(url)) {
1049    <span class="hljs-comment">// CoffeeScript files can be either CommonJS or ES modules, so we want any</span>
1050    <span class="hljs-comment">// CoffeeScript file to be treated by Node.js the same as a .js file at the</span>
1051    <span class="hljs-comment">// same location. To determine how Node.js would interpret an arbitrary .js</span>
1052    <span class="hljs-comment">// file, search up the file system for the nearest parent package.json file</span>
1053    <span class="hljs-comment">// and read its "type" field.</span>
1054    <span class="hljs-keyword">const</span> format = <span class="hljs-keyword">await</span> <span class="hljs-title function_">getPackageType</span>(url);
1055
1056    <span class="hljs-keyword">const</span> { <span class="hljs-attr">source</span>: rawSource } = <span class="hljs-keyword">await</span> <span class="hljs-title function_">nextLoad</span>(url, { ...context, format });
1057    <span class="hljs-comment">// This hook converts CoffeeScript source code into JavaScript source code</span>
1058    <span class="hljs-comment">// for all imported CoffeeScript files.</span>
1059    <span class="hljs-keyword">const</span> transformedSource = coffeescript.<span class="hljs-title function_">compile</span>(rawSource.<span class="hljs-title function_">toString</span>(), url);
1060
1061    <span class="hljs-keyword">return</span> {
1062      format,
1063      <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
1064      <span class="hljs-attr">source</span>: transformedSource,
1065    };
1066  }
1067
1068  <span class="hljs-comment">// Let Node.js handle all other URLs.</span>
1069  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url);
1070}
1071
1072<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getPackageType</span>(<span class="hljs-params">url</span>) {
1073  <span class="hljs-comment">// `url` is only a file path during the first iteration when passed the</span>
1074  <span class="hljs-comment">// resolved url from the load() hook</span>
1075  <span class="hljs-comment">// an actual file path from load() will contain a file extension as it's</span>
1076  <span class="hljs-comment">// required by the spec</span>
1077  <span class="hljs-comment">// this simple truthy check for whether `url` contains a file extension will</span>
1078  <span class="hljs-comment">// work for most projects but does not cover some edge-cases (such as</span>
1079  <span class="hljs-comment">// extensionless files or a url ending in a trailing space)</span>
1080  <span class="hljs-keyword">const</span> isFilePath = !!<span class="hljs-title function_">extname</span>(url);
1081  <span class="hljs-comment">// If it is a file path, get the directory it's in</span>
1082  <span class="hljs-keyword">const</span> dir = isFilePath ?
1083    <span class="hljs-title function_">dirname</span>(<span class="hljs-title function_">fileURLToPath</span>(url)) :
1084    url;
1085  <span class="hljs-comment">// Compose a file path to a package.json in the same directory,</span>
1086  <span class="hljs-comment">// which may or may not exist</span>
1087  <span class="hljs-keyword">const</span> packagePath = <span class="hljs-title function_">resolvePath</span>(dir, <span class="hljs-string">'package.json'</span>);
1088  <span class="hljs-comment">// Try to read the possibly nonexistent package.json</span>
1089  <span class="hljs-keyword">const</span> type = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readFile</span>(packagePath, { <span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span> })
1090    .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">filestring</span>) =></span> <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(filestring).<span class="hljs-property">type</span>)
1091    .<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
1092      <span class="hljs-keyword">if</span> (err?.<span class="hljs-property">code</span> !== <span class="hljs-string">'ENOENT'</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
1093    });
1094  <span class="hljs-comment">// Ff package.json existed and contained a `type` field with a value, voila</span>
1095  <span class="hljs-keyword">if</span> (type) <span class="hljs-keyword">return</span> type;
1096  <span class="hljs-comment">// Otherwise, (if not at the root) continue checking the next directory up</span>
1097  <span class="hljs-comment">// If at the root, stop and return false</span>
1098  <span class="hljs-keyword">return</span> dir.<span class="hljs-property">length</span> > <span class="hljs-number">1</span> &#x26;&#x26; <span class="hljs-title function_">getPackageType</span>(<span class="hljs-title function_">resolvePath</span>(dir, <span class="hljs-string">'..'</span>));
1099}</code> <button class="copy-button">copy</button></pre>
1100<pre><code class="language-coffee"><span class="hljs-comment"># main.coffee</span>
1101<span class="hljs-keyword">import</span> { scream } <span class="hljs-keyword">from</span> <span class="hljs-string">'./scream.coffee'</span>
1102console.log scream <span class="hljs-string">'hello, world'</span>
1103
1104<span class="hljs-keyword">import</span> { version } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>
1105console.log <span class="hljs-string">"Brought to you by Node.js version <span class="hljs-subst">#{version}</span>"</span></code> <button class="copy-button">copy</button></pre>
1106<pre><code class="language-coffee"><span class="hljs-comment"># scream.coffee</span>
1107<span class="hljs-keyword">export</span> scream = <span class="hljs-function"><span class="hljs-params">(str)</span> -></span> str.toUpperCase()</code> <button class="copy-button">copy</button></pre>
1108<p>With the preceding hooks module, running
1109<code>node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./coffeescript-hooks.mjs"));' ./main.coffee</code>
1110causes <code>main.coffee</code> to be turned into JavaScript after its source code is
1111loaded from disk but before Node.js executes it; and so on for any <code>.coffee</code>,
1112<code>.litcoffee</code> or <code>.coffee.md</code> files referenced via <code>import</code> statements of any
1113loaded file.</p>
1114<h5>Import maps<span><a class="mark" href="#import-maps" id="import-maps">#</a></span><a aria-hidden="true" class="legacy" id="module_import_maps"></a></h5>
1115<p>The previous two examples defined <code>load</code> hooks. This is an example of a
1116<code>resolve</code> hook. This hooks module reads an <code>import-map.json</code> file that defines
1117which specifiers to override to other URLs (this is a very simplistic
1118implementation of a small subset of the "import maps" specification).</p>
1119<pre><code class="language-js mjs"><span class="hljs-comment">// import-map-hooks.js</span>
1120<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
1121
1122<span class="hljs-keyword">const</span> { imports } = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(<span class="hljs-keyword">await</span> fs.<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'import-map.json'</span>));
1123
1124<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) {
1125  <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">hasOwn</span>(imports, specifier)) {
1126    <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(imports[specifier], context);
1127  }
1128
1129  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier, context);
1130}</code> <button class="copy-button">copy</button></pre>
1131<p>With these files:</p>
1132<pre><code class="language-js mjs"><span class="hljs-comment">// main.js</span>
1133<span class="hljs-keyword">import</span> <span class="hljs-string">'a-module'</span>;</code> <button class="copy-button">copy</button></pre>
1134<pre><code class="language-json"><span class="hljs-comment">// import-map.json</span>
1135<span class="hljs-punctuation">{</span>
1136  <span class="hljs-attr">"imports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
1137    <span class="hljs-attr">"a-module"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./some-module.js"</span>
1138  <span class="hljs-punctuation">}</span>
1139<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
1140<pre><code class="language-js mjs"><span class="hljs-comment">// some-module.js</span>
1141<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'some module!'</span>);</code> <button class="copy-button">copy</button></pre>
1142<p>Running <code>node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./import-map-hooks.js"));' main.js</code>
1143should print <code>some module!</code>.</p>
1144</section><section><h3>Source map v3 support<span><a class="mark" href="#source-map-v3-support" id="source-map-v3-support">#</a></span><a aria-hidden="true" class="legacy" id="module_source_map_v3_support"></a></h3>
1145<div class="api_metadata">
1146<span>Added in: v13.7.0, v12.17.0</span>
1147</div>
1148<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
1149<p>Helpers for interacting with the source map cache. This cache is
1150populated when source map parsing is enabled and
1151<a href="https://sourcemaps.info/spec.html#h.lmz475t4mvbx">source map include directives</a> are found in a modules' footer.</p>
1152<p>To enable source map parsing, Node.js must be run with the flag
1153<a href="cli.html#--enable-source-maps"><code>--enable-source-maps</code></a>, or with code coverage enabled by setting
1154<a href="cli.html#node_v8_coveragedir"><code>NODE_V8_COVERAGE=dir</code></a>.</p>
1155
1156<pre class="with-26-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// module.mjs</span>
1157<span class="hljs-comment">// In an ECMAScript module</span>
1158<span class="hljs-keyword">import</span> { findSourceMap, <span class="hljs-title class_">SourceMap</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;</code><code class="language-js cjs"><span class="hljs-comment">// module.cjs</span>
1159<span class="hljs-comment">// In a CommonJS module</span>
1160<span class="hljs-keyword">const</span> { findSourceMap, <span class="hljs-title class_">SourceMap</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);</code><button class="copy-button">copy</button></pre>
1161<!-- Anchors to make sure old links find a target -->
1162<p><a id="module_module_findsourcemap_path_error"></a></p>
1163<h4><code>module.findSourceMap(path)</code><span><a class="mark" href="#modulefindsourcemappath" id="modulefindsourcemappath">#</a></span><a aria-hidden="true" class="legacy" id="module_module_findsourcemap_path"></a></h4>
1164<div class="api_metadata">
1165<span>Added in: v13.7.0, v12.17.0</span>
1166</div>
1167<ul>
1168<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
1169<li>Returns: <a href="module.html#class-modulesourcemap" class="type">&#x3C;module.SourceMap></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> Returns <code>module.SourceMap</code> if a source
1170map is found, <code>undefined</code> otherwise.</li>
1171</ul>
1172<p><code>path</code> is the resolved path for the file for which a corresponding source map
1173should be fetched.</p>
1174<h4>Class: <code>module.SourceMap</code><span><a class="mark" href="#class-modulesourcemap" id="class-modulesourcemap">#</a></span><a aria-hidden="true" class="legacy" id="module_class_module_sourcemap"></a></h4>
1175<div class="api_metadata">
1176<span>Added in: v13.7.0, v12.17.0</span>
1177</div>
1178<h5><code>new SourceMap(payload)</code><span><a class="mark" href="#new-sourcemappayload" id="new-sourcemappayload">#</a></span><a aria-hidden="true" class="legacy" id="module_new_sourcemap_payload"></a></h5>
1179<ul>
1180<li><code>payload</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
1181</ul>
1182<p>Creates a new <code>sourceMap</code> instance.</p>
1183<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>
1184<ul>
1185<li><code>file</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
1186<li><code>version</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
1187<li><code>sources</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
1188<li><code>sourcesContent</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
1189<li><code>names</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
1190<li><code>mappings</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
1191<li><code>sourceRoot</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
1192</ul>
1193<h5><code>sourceMap.payload</code><span><a class="mark" href="#sourcemappayload" id="sourcemappayload">#</a></span><a aria-hidden="true" class="legacy" id="module_sourcemap_payload"></a></h5>
1194<ul>
1195<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
1196</ul>
1197<p>Getter for the payload used to construct the <a href="#class-modulesourcemap"><code>SourceMap</code></a> instance.</p>
1198<h5><code>sourceMap.findEntry(lineOffset, columnOffset)</code><span><a class="mark" href="#sourcemapfindentrylineoffset-columnoffset" id="sourcemapfindentrylineoffset-columnoffset">#</a></span><a aria-hidden="true" class="legacy" id="module_sourcemap_findentry_lineoffset_columnoffset"></a></h5>
1199<ul>
1200<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The zero-indexed line number offset in
1201the generated source</li>
1202<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The zero-indexed column number offset
1203in the generated source</li>
1204<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
1205</ul>
1206<p>Given a line offset and column offset in the generated source
1207file, returns an object representing the SourceMap range in the
1208original file if found, or an empty object if not.</p>
1209<p>The object returned contains the following keys:</p>
1210<ul>
1211<li>generatedLine: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The line offset of the start of the
1212range in the generated source</li>
1213<li>generatedColumn: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The column offset of start of the
1214range in the generated source</li>
1215<li>originalSource: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The file name of the original source,
1216as reported in the SourceMap</li>
1217<li>originalLine: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The line offset of the start of the
1218range in the original source</li>
1219<li>originalColumn: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The column offset of start of the
1220range in the original source</li>
1221<li>name: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
1222</ul>
1223<p>The returned value represents the raw range as it appears in the
1224SourceMap, based on zero-indexed offsets, <em>not</em> 1-indexed line and
1225column numbers as they appear in Error messages and CallSite
1226objects.</p>
1227<p>To get the corresponding 1-indexed line and column numbers from a
1228lineNumber and columnNumber as they are reported by Error stacks
1229and CallSite objects, use <code>sourceMap.findOrigin(lineNumber, columnNumber)</code></p>
1230<h5><code>sourceMap.findOrigin(lineNumber, columnNumber)</code><span><a class="mark" href="#sourcemapfindoriginlinenumber-columnnumber" id="sourcemapfindoriginlinenumber-columnnumber">#</a></span><a aria-hidden="true" class="legacy" id="module_sourcemap_findorigin_linenumber_columnnumber"></a></h5>
1231<ul>
1232<li><code>lineNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The 1-indexed line number of the call
1233site in the generated source</li>
1234<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The 1-indexed column number
1235of the call site in the generated source</li>
1236<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
1237</ul>
1238<p>Given a 1-indexed lineNumber and columnNumber from a call site in
1239the generated source, find the corresponding call site location
1240in the original source.</p>
1241<p>If the lineNumber and columnNumber provided are not found in any
1242source map, then an empty object is returned.  Otherwise, the
1243returned object contains the following keys:</p>
1244<ul>
1245<li>name: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The name of the range in the
1246source map, if one was provided</li>
1247<li>fileName: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The file name of the original source, as
1248reported in the SourceMap</li>
1249<li>lineNumber: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The 1-indexed lineNumber of the
1250corresponding call site in the original source</li>
1251<li>columnNumber: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The 1-indexed columnNumber of the
1252corresponding call site in the original source</li>
1253</ul></section>
1254        <!-- API END -->
1255      </div>
1256    </div>
1257  </div>
1258</body>
1259</html>
1260