📁 File Manager Pro
v10.0.3 | PHP: 8.1.34
Server: Apache
2026-06-22 23:13:07
📂
/ (Root)
/
opt
/
alt
/
alt-nodejs24
/
root
/
usr
/
share
/
doc
/
alt-nodejs24-nodejs-docs-24.15.0
/
html
/
api
📍 /opt/alt/alt-nodejs24/root/usr/share/doc/alt-nodejs24-nodejs-docs-24.15.0/html/api
🔄 Refresh
✏️
Editing: module.html
Read Only
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <meta name="nodejs.org:node-version" content="v24.15.0"> <title>Modules: node:module API | Node.js v24.15.0 Documentation</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback"> <link rel="stylesheet" href="assets/style.css"> <link rel="stylesheet" href="assets/hljs.css"> <link rel="canonical" href="https://nodejs.org/api/module.html"> <script async defer src="assets/api.js" type="text/javascript"></script> <script> const storedTheme = localStorage.getItem('theme'); // Follow operating system theme preference if (storedTheme === null && window.matchMedia) { const mq = window.matchMedia('(prefers-color-scheme: dark)'); if (mq.matches) { document.documentElement.classList.add('dark-mode'); } } else if (storedTheme === 'dark') { document.documentElement.classList.add('dark-mode'); } </script> <style>@media(max-width:430px){.with-26-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:630px){.with-51-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:670px){.with-56-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:614px){.with-49-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1120px){.with-78-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:574px){.with-44-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:646px){.with-53-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}</style> </head> <body class="alt apidoc" id="api-section-module"> <a href="#apicontent" class="skip-to-content">Skip to content</a> <div id="content" class="clearfix"> <div role="navigation" id="column2" class="interior"> <div id="intro" class="interior"> <a href="/" title="Go back to the home page"> Node.js </a> </div> <ul> <li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> <li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> </ul> <hr class="line"> <ul> <li><a href="assert.html" class="nav-assert">Assertion testing</a></li> <li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li> <li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> <li><a href="buffer.html" class="nav-buffer">Buffer</a></li> <li><a href="addons.html" class="nav-addons">C++ addons</a></li> <li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> <li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> <li><a href="child_process.html" class="nav-child_process">Child processes</a></li> <li><a href="cluster.html" class="nav-cluster">Cluster</a></li> <li><a href="cli.html" class="nav-cli">Command-line options</a></li> <li><a href="console.html" class="nav-console">Console</a></li> <li><a href="crypto.html" class="nav-crypto">Crypto</a></li> <li><a href="debugger.html" class="nav-debugger">Debugger</a></li> <li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> <li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> <li><a href="dns.html" class="nav-dns">DNS</a></li> <li><a href="domain.html" class="nav-domain">Domain</a></li> <li><a href="environment_variables.html" class="nav-environment_variables">Environment Variables</a></li> <li><a href="errors.html" class="nav-errors">Errors</a></li> <li><a href="events.html" class="nav-events">Events</a></li> <li><a href="fs.html" class="nav-fs">File system</a></li> <li><a href="globals.html" class="nav-globals">Globals</a></li> <li><a href="http.html" class="nav-http">HTTP</a></li> <li><a href="http2.html" class="nav-http2">HTTP/2</a></li> <li><a href="https.html" class="nav-https">HTTPS</a></li> <li><a href="inspector.html" class="nav-inspector">Inspector</a></li> <li><a href="intl.html" class="nav-intl">Internationalization</a></li> <li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> <li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> <li><a href="module.html" class="nav-module active">Modules: <code>node:module</code> API</a></li> <li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> <li><a href="typescript.html" class="nav-typescript">Modules: TypeScript</a></li> <li><a href="net.html" class="nav-net">Net</a></li> <li><a href="os.html" class="nav-os">OS</a></li> <li><a href="path.html" class="nav-path">Path</a></li> <li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> <li><a href="permissions.html" class="nav-permissions">Permissions</a></li> <li><a href="process.html" class="nav-process">Process</a></li> <li><a href="punycode.html" class="nav-punycode">Punycode</a></li> <li><a href="querystring.html" class="nav-querystring">Query strings</a></li> <li><a href="readline.html" class="nav-readline">Readline</a></li> <li><a href="repl.html" class="nav-repl">REPL</a></li> <li><a href="report.html" class="nav-report">Report</a></li> <li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li> <li><a href="sqlite.html" class="nav-sqlite">SQLite</a></li> <li><a href="stream.html" class="nav-stream">Stream</a></li> <li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> <li><a href="test.html" class="nav-test">Test runner</a></li> <li><a href="timers.html" class="nav-timers">Timers</a></li> <li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> <li><a href="tracing.html" class="nav-tracing">Trace events</a></li> <li><a href="tty.html" class="nav-tty">TTY</a></li> <li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li> <li><a href="url.html" class="nav-url">URL</a></li> <li><a href="util.html" class="nav-util">Utilities</a></li> <li><a href="v8.html" class="nav-v8">V8</a></li> <li><a href="vm.html" class="nav-vm">VM</a></li> <li><a href="wasi.html" class="nav-wasi">WASI</a></li> <li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li> <li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li> <li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li> <li><a href="zlib.html" class="nav-zlib">Zlib</a></li> </ul> <hr class="line"> <ul> <li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> </ul> </div> <div id="column1" data-id="module" class="interior"> <header class="header"> <div class="header-container"> <h1>Node.js v24.15.0 documentation</h1> <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden> <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24"> <path fill="none" d="M0 0h24v24H0z" /> <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"/> <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"/> </svg> <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24"> <path d="M0 0h24v24H0z" fill="none" /> <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"/> </svg> </button> </div> <div id="gtoc"> <ul> <li class="pinned-header">Node.js v24.15.0</li> <li class="picker-header"> <a href="#toc-picker" aria-controls="toc-picker"> <span class="picker-arrow"></span> Table of contents </a> <div class="picker" tabindex="-1"><div class="toc"><ul id="toc-picker"> <li><a href="#modules-nodemodule-api">Modules: <code>node:module</code> API</a> <ul> <li><a href="#the-module-object">The <code>Module</code> object</a> <ul> <li><a href="#modulebuiltinmodules"><code>module.builtinModules</code></a></li> <li><a href="#modulecreaterequirefilename"><code>module.createRequire(filename)</code></a></li> <li><span class="stability_1.1"><a href="#modulefindpackagejsonspecifier-base"><code>module.findPackageJSON(specifier[, base])</code></a></span></li> <li><a href="#moduleisbuiltinmodulename"><code>module.isBuiltin(moduleName)</code></a></li> <li><span class="stability_0"><a href="#moduleregisterspecifier-parenturl-options"><code>module.register(specifier[, parentURL][, options])</code></a></span></li> <li><span class="stability_1.2"><a href="#moduleregisterhooksoptions"><code>module.registerHooks(options)</code></a></span></li> <li><span class="stability_1.2"><a href="#modulestriptypescripttypescode-options"><code>module.stripTypeScriptTypes(code[, options])</code></a></span></li> <li><a href="#modulesyncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a></li> </ul> </li> <li><a href="#module-compile-cache">Module compile cache</a> <ul> <li><a href="#portability-of-the-compile-cache">Portability of the compile cache</a></li> <li><a href="#limitations-of-the-compile-cache">Limitations of the compile cache</a></li> <li><a href="#moduleconstantscompilecachestatus"><code>module.constants.compileCacheStatus</code></a></li> <li><a href="#moduleenablecompilecacheoptions"><code>module.enableCompileCache([options])</code></a></li> <li><a href="#moduleflushcompilecache"><code>module.flushCompileCache()</code></a></li> <li><a href="#modulegetcompilecachedir"><code>module.getCompileCacheDir()</code></a></li> </ul> </li> <li><a href="#customization-hooks">Customization Hooks</a> <ul> <li><span class="stability_1.2"><a href="#synchronous-customization-hooks">Synchronous customization hooks</a></span> <ul> <li><a href="#registration-of-synchronous-customization-hooks">Registration of synchronous customization hooks</a> <ul> <li><a href="#registering-hooks-before-application-code-runs-with-flags">Registering hooks before application code runs with flags</a></li> <li><a href="#registering-hooks-before-application-code-runs-programmatically">Registering hooks before application code runs programmatically</a></li> <li><a href="#registering-hooks-before-application-code-runs-with-a-data-url">Registering hooks before application code runs with a <code>data:</code> URL</a></li> </ul> </li> <li><a href="#convention-of-hooks-and-chaining">Convention of hooks and chaining</a></li> <li><a href="#deregistration-of-synchronous-customization-hooks">Deregistration of synchronous customization hooks</a></li> <li><a href="#hook-functions-accepted-by-moduleregisterhooks">Hook functions accepted by <code>module.registerHooks()</code></a></li> <li><a href="#synchronous-resolvespecifier-context-nextresolve">Synchronous <code>resolve(specifier, context, nextResolve)</code></a></li> <li><a href="#synchronous-loadurl-context-nextload">Synchronous <code>load(url, context, nextLoad)</code></a> <ul> <li><a href="#accepted-final-formats-returned-by-load">Accepted final formats returned by <code>load</code></a></li> </ul> </li> </ul> </li> <li><span class="stability_1.1"><a href="#asynchronous-customization-hooks">Asynchronous customization hooks</a></span> <ul> <li><a href="#caveats-of-asynchronous-customization-hooks">Caveats of asynchronous customization hooks</a></li> <li><a href="#registration-of-asynchronous-customization-hooks">Registration of asynchronous customization hooks</a></li> <li><a href="#chaining-of-asynchronous-customization-hooks">Chaining of asynchronous customization hooks</a></li> <li><a href="#communication-with-asynchronous-module-customization-hooks">Communication with asynchronous module customization hooks</a></li> <li><a href="#asynchronous-hooks-accepted-by-moduleregister">Asynchronous hooks accepted by <code>module.register()</code></a></li> <li><a href="#initialize"><code>initialize()</code></a></li> <li><a href="#asynchronous-resolvespecifier-context-nextresolve">Asynchronous <code>resolve(specifier, context, nextResolve)</code></a></li> <li><a href="#asynchronous-loadurl-context-nextload">Asynchronous <code>load(url, context, nextLoad)</code></a></li> </ul> </li> <li><a href="#examples">Examples</a> <ul> <li><a href="#import-from-https">Import from HTTPS</a></li> <li><a href="#transpilation">Transpilation</a> <ul> <li><a href="#asynchronous-version">Asynchronous version</a></li> <li><a href="#synchronous-version">Synchronous version</a></li> </ul> </li> <li><a href="#running-hooks">Running hooks</a></li> <li><a href="#import-maps">Import maps</a> <ul> <li><a href="#asynchronous-version_1">Asynchronous version</a></li> <li><a href="#synchronous-version_1">Synchronous version</a></li> <li><a href="#using-the-hooks">Using the hooks</a></li> </ul> </li> </ul> </li> </ul> </li> <li><span class="stability_1"><a href="#source-map-support">Source Map Support</a></span> <ul> <li><a href="#modulegetsourcemapssupport"><code>module.getSourceMapsSupport()</code></a></li> <li><a href="#modulefindsourcemappath"><code>module.findSourceMap(path)</code></a></li> <li><a href="#modulesetsourcemapssupportenabled-options"><code>module.setSourceMapsSupport(enabled[, options])</code></a></li> <li><a href="#class-modulesourcemap">Class: <code>module.SourceMap</code></a> <ul> <li><a href="#new-sourcemappayload--linelengths-"><code>new SourceMap(payload[, { lineLengths }])</code></a></li> <li><a href="#sourcemappayload"><code>sourceMap.payload</code></a></li> <li><a href="#sourcemapfindentrylineoffset-columnoffset"><code>sourceMap.findEntry(lineOffset, columnOffset)</code></a></li> <li><a href="#sourcemapfindoriginlinenumber-columnnumber"><code>sourceMap.findOrigin(lineNumber, columnNumber)</code></a></li> </ul> </li> </ul> </li> </ul> </li> </ul></div></div> </li> <li class="picker-header"> <a href="#gtoc-picker" aria-controls="gtoc-picker"> <span class="picker-arrow"></span> Index </a> <div class="picker" tabindex="-1" id="gtoc-picker"><ul> <li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> <li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> <li> <a href="index.html">Index</a> </li> </ul> <hr class="line"> <ul> <li><a href="assert.html" class="nav-assert">Assertion testing</a></li> <li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li> <li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> <li><a href="buffer.html" class="nav-buffer">Buffer</a></li> <li><a href="addons.html" class="nav-addons">C++ addons</a></li> <li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> <li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> <li><a href="child_process.html" class="nav-child_process">Child processes</a></li> <li><a href="cluster.html" class="nav-cluster">Cluster</a></li> <li><a href="cli.html" class="nav-cli">Command-line options</a></li> <li><a href="console.html" class="nav-console">Console</a></li> <li><a href="crypto.html" class="nav-crypto">Crypto</a></li> <li><a href="debugger.html" class="nav-debugger">Debugger</a></li> <li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> <li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> <li><a href="dns.html" class="nav-dns">DNS</a></li> <li><a href="domain.html" class="nav-domain">Domain</a></li> <li><a href="environment_variables.html" class="nav-environment_variables">Environment Variables</a></li> <li><a href="errors.html" class="nav-errors">Errors</a></li> <li><a href="events.html" class="nav-events">Events</a></li> <li><a href="fs.html" class="nav-fs">File system</a></li> <li><a href="globals.html" class="nav-globals">Globals</a></li> <li><a href="http.html" class="nav-http">HTTP</a></li> <li><a href="http2.html" class="nav-http2">HTTP/2</a></li> <li><a href="https.html" class="nav-https">HTTPS</a></li> <li><a href="inspector.html" class="nav-inspector">Inspector</a></li> <li><a href="intl.html" class="nav-intl">Internationalization</a></li> <li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> <li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> <li><a href="module.html" class="nav-module active">Modules: <code>node:module</code> API</a></li> <li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> <li><a href="typescript.html" class="nav-typescript">Modules: TypeScript</a></li> <li><a href="net.html" class="nav-net">Net</a></li> <li><a href="os.html" class="nav-os">OS</a></li> <li><a href="path.html" class="nav-path">Path</a></li> <li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> <li><a href="permissions.html" class="nav-permissions">Permissions</a></li> <li><a href="process.html" class="nav-process">Process</a></li> <li><a href="punycode.html" class="nav-punycode">Punycode</a></li> <li><a href="querystring.html" class="nav-querystring">Query strings</a></li> <li><a href="readline.html" class="nav-readline">Readline</a></li> <li><a href="repl.html" class="nav-repl">REPL</a></li> <li><a href="report.html" class="nav-report">Report</a></li> <li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li> <li><a href="sqlite.html" class="nav-sqlite">SQLite</a></li> <li><a href="stream.html" class="nav-stream">Stream</a></li> <li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> <li><a href="test.html" class="nav-test">Test runner</a></li> <li><a href="timers.html" class="nav-timers">Timers</a></li> <li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> <li><a href="tracing.html" class="nav-tracing">Trace events</a></li> <li><a href="tty.html" class="nav-tty">TTY</a></li> <li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li> <li><a href="url.html" class="nav-url">URL</a></li> <li><a href="util.html" class="nav-util">Utilities</a></li> <li><a href="v8.html" class="nav-v8">V8</a></li> <li><a href="vm.html" class="nav-vm">VM</a></li> <li><a href="wasi.html" class="nav-wasi">WASI</a></li> <li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li> <li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li> <li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li> <li><a href="zlib.html" class="nav-zlib">Zlib</a></li> </ul> <hr class="line"> <ul> <li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> </ul></div> </li> <li class="picker-header"> <a href="#alt-docs" aria-controls="alt-docs"> <span class="picker-arrow"></span> Other versions </a> <div class="picker" tabindex="-1"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v25.x/api/module.html">25.x</a></li> <li><a href="https://nodejs.org/docs/latest-v24.x/api/module.html">24.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v23.x/api/module.html">23.x</a></li> <li><a href="https://nodejs.org/docs/latest-v22.x/api/module.html">22.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v21.x/api/module.html">21.x</a></li> <li><a href="https://nodejs.org/docs/latest-v20.x/api/module.html">20.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v19.x/api/module.html">19.x</a></li> <li><a href="https://nodejs.org/docs/latest-v18.x/api/module.html">18.x</a></li> <li><a href="https://nodejs.org/docs/latest-v17.x/api/module.html">17.x</a></li> <li><a href="https://nodejs.org/docs/latest-v16.x/api/module.html">16.x</a></li> <li><a href="https://nodejs.org/docs/latest-v15.x/api/module.html">15.x</a></li> <li><a href="https://nodejs.org/docs/latest-v14.x/api/module.html">14.x</a></li> <li><a href="https://nodejs.org/docs/latest-v13.x/api/module.html">13.x</a></li> <li><a href="https://nodejs.org/docs/latest-v12.x/api/module.html">12.x</a></li></ol></div> </li> <li class="picker-header"> <a href="#options-picker" aria-controls="options-picker"> <span class="picker-arrow"></span> Options </a> <div class="picker" tabindex="-1"> <ul id="options-picker"> <li> <a href="all.html">View on single page</a> </li> <li> <a href="module.json">View as JSON</a> </li> <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/main/doc/api/module.md">Edit on GitHub</a></li> </ul> </div> </li> </ul> </div> <hr> </header> <details role="navigation" id="toc" open><summary>Table of contents</summary><ul> <li><a href="#modules-nodemodule-api">Modules: <code>node:module</code> API</a> <ul> <li><a href="#the-module-object">The <code>Module</code> object</a> <ul> <li><a href="#modulebuiltinmodules"><code>module.builtinModules</code></a></li> <li><a href="#modulecreaterequirefilename"><code>module.createRequire(filename)</code></a></li> <li><span class="stability_1.1"><a href="#modulefindpackagejsonspecifier-base"><code>module.findPackageJSON(specifier[, base])</code></a></span></li> <li><a href="#moduleisbuiltinmodulename"><code>module.isBuiltin(moduleName)</code></a></li> <li><span class="stability_0"><a href="#moduleregisterspecifier-parenturl-options"><code>module.register(specifier[, parentURL][, options])</code></a></span></li> <li><span class="stability_1.2"><a href="#moduleregisterhooksoptions"><code>module.registerHooks(options)</code></a></span></li> <li><span class="stability_1.2"><a href="#modulestriptypescripttypescode-options"><code>module.stripTypeScriptTypes(code[, options])</code></a></span></li> <li><a href="#modulesyncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a></li> </ul> </li> <li><a href="#module-compile-cache">Module compile cache</a> <ul> <li><a href="#portability-of-the-compile-cache">Portability of the compile cache</a></li> <li><a href="#limitations-of-the-compile-cache">Limitations of the compile cache</a></li> <li><a href="#moduleconstantscompilecachestatus"><code>module.constants.compileCacheStatus</code></a></li> <li><a href="#moduleenablecompilecacheoptions"><code>module.enableCompileCache([options])</code></a></li> <li><a href="#moduleflushcompilecache"><code>module.flushCompileCache()</code></a></li> <li><a href="#modulegetcompilecachedir"><code>module.getCompileCacheDir()</code></a></li> </ul> </li> <li><a href="#customization-hooks">Customization Hooks</a> <ul> <li><span class="stability_1.2"><a href="#synchronous-customization-hooks">Synchronous customization hooks</a></span> <ul> <li><a href="#registration-of-synchronous-customization-hooks">Registration of synchronous customization hooks</a> <ul> <li><a href="#registering-hooks-before-application-code-runs-with-flags">Registering hooks before application code runs with flags</a></li> <li><a href="#registering-hooks-before-application-code-runs-programmatically">Registering hooks before application code runs programmatically</a></li> <li><a href="#registering-hooks-before-application-code-runs-with-a-data-url">Registering hooks before application code runs with a <code>data:</code> URL</a></li> </ul> </li> <li><a href="#convention-of-hooks-and-chaining">Convention of hooks and chaining</a></li> <li><a href="#deregistration-of-synchronous-customization-hooks">Deregistration of synchronous customization hooks</a></li> <li><a href="#hook-functions-accepted-by-moduleregisterhooks">Hook functions accepted by <code>module.registerHooks()</code></a></li> <li><a href="#synchronous-resolvespecifier-context-nextresolve">Synchronous <code>resolve(specifier, context, nextResolve)</code></a></li> <li><a href="#synchronous-loadurl-context-nextload">Synchronous <code>load(url, context, nextLoad)</code></a> <ul> <li><a href="#accepted-final-formats-returned-by-load">Accepted final formats returned by <code>load</code></a></li> </ul> </li> </ul> </li> <li><span class="stability_1.1"><a href="#asynchronous-customization-hooks">Asynchronous customization hooks</a></span> <ul> <li><a href="#caveats-of-asynchronous-customization-hooks">Caveats of asynchronous customization hooks</a></li> <li><a href="#registration-of-asynchronous-customization-hooks">Registration of asynchronous customization hooks</a></li> <li><a href="#chaining-of-asynchronous-customization-hooks">Chaining of asynchronous customization hooks</a></li> <li><a href="#communication-with-asynchronous-module-customization-hooks">Communication with asynchronous module customization hooks</a></li> <li><a href="#asynchronous-hooks-accepted-by-moduleregister">Asynchronous hooks accepted by <code>module.register()</code></a></li> <li><a href="#initialize"><code>initialize()</code></a></li> <li><a href="#asynchronous-resolvespecifier-context-nextresolve">Asynchronous <code>resolve(specifier, context, nextResolve)</code></a></li> <li><a href="#asynchronous-loadurl-context-nextload">Asynchronous <code>load(url, context, nextLoad)</code></a></li> </ul> </li> <li><a href="#examples">Examples</a> <ul> <li><a href="#import-from-https">Import from HTTPS</a></li> <li><a href="#transpilation">Transpilation</a> <ul> <li><a href="#asynchronous-version">Asynchronous version</a></li> <li><a href="#synchronous-version">Synchronous version</a></li> </ul> </li> <li><a href="#running-hooks">Running hooks</a></li> <li><a href="#import-maps">Import maps</a> <ul> <li><a href="#asynchronous-version_1">Asynchronous version</a></li> <li><a href="#synchronous-version_1">Synchronous version</a></li> <li><a href="#using-the-hooks">Using the hooks</a></li> </ul> </li> </ul> </li> </ul> </li> <li><span class="stability_1"><a href="#source-map-support">Source Map Support</a></span> <ul> <li><a href="#modulegetsourcemapssupport"><code>module.getSourceMapsSupport()</code></a></li> <li><a href="#modulefindsourcemappath"><code>module.findSourceMap(path)</code></a></li> <li><a href="#modulesetsourcemapssupportenabled-options"><code>module.setSourceMapsSupport(enabled[, options])</code></a></li> <li><a href="#class-modulesourcemap">Class: <code>module.SourceMap</code></a> <ul> <li><a href="#new-sourcemappayload--linelengths-"><code>new SourceMap(payload[, { lineLengths }])</code></a></li> <li><a href="#sourcemappayload"><code>sourceMap.payload</code></a></li> <li><a href="#sourcemapfindentrylineoffset-columnoffset"><code>sourceMap.findEntry(lineOffset, columnOffset)</code></a></li> <li><a href="#sourcemapfindoriginlinenumber-columnnumber"><code>sourceMap.findOrigin(lineNumber, columnNumber)</code></a></li> </ul> </li> </ul> </li> </ul> </li> </ul></details> <div role="main" id="apicontent"> <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> <div class="api_metadata"> <span>Added in: v0.3.7</span> </div> <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> <ul> <li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Provides general utility methods when interacting with instances of <code>Module</code>, the <a href="#the-module-object"><code>module</code></a> variable often seen in <a href="modules.html">CommonJS</a> modules. Accessed via <code>import 'node:module'</code> or <code>require('node:module')</code>.</p> <div> <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> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v23.5.0</td> <td><p>The list now also contains prefix-only modules.</p></td></tr> <tr><td>v9.3.0, v8.10.0, v6.13.0</td> <td><p><span>Added in: v9.3.0, v8.10.0, v6.13.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string[]></a></li> </ul> <p>A list of the names of all modules provided by Node.js. Can be used to verify if a module is maintained by a third party or not.</p> <p><code>module</code> in this context isn't the same object that's provided by the <a href="modules.html#the-module-wrapper">module wrapper</a>. To access it, require the <code>Module</code> module:</p> <pre class="with-26-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// module.mjs</span> <span class="hljs-comment">// In an ECMAScript module</span> <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> <span class="hljs-comment">// In a CommonJS module</span> <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> </div><div> <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> <div class="api_metadata"> <span>Added in: v12.2.0</span> </div> <ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="url.html#the-whatwg-url-api" class="type"><URL></a> Filename to be used to construct the require function. Must be a file URL object, file URL string, or absolute path string.</li> <li>Returns: <a href="modules.html#requireid" class="type"><require></a> Require function</li> </ul> <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>; <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>); <span class="hljs-comment">// sibling-module.js is a CommonJS module.</span> <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> </div><div> <h4><code>module.findPackageJSON(specifier[, base])</code><span><a class="mark" href="#modulefindpackagejsonspecifier-base" id="modulefindpackagejsonspecifier-base">#</a></span><a aria-hidden="true" class="legacy" id="module_module_findpackagejson_specifier_base"></a></h4> <div class="api_metadata"> <span>Added in: v23.2.0, v22.14.0</span> </div> <p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1.1</a> - Active Development</div><p></p> <ul> <li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="url.html#the-whatwg-url-api" class="type"><URL></a> The specifier for the module whose <code>package.json</code> to retrieve. When passing a <em>bare specifier</em>, the <code>package.json</code> at the root of the package is returned. When passing a <em>relative specifier</em> or an <em>absolute specifier</em>, the closest parent <code>package.json</code> is returned.</li> <li><code>base</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="url.html#the-whatwg-url-api" class="type"><URL></a> The absolute location (<code>file:</code> URL string or FS path) of the containing module. For CJS, use <code>__filename</code> (not <code>__dirname</code>!); for ESM, use <code>import.meta.url</code>. You do not need to pass it if <code>specifier</code> is an <code>absolute specifier</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> A path if the <code>package.json</code> is found. When <code>specifier</code> is a package, the package's root <code>package.json</code>; when a relative or unresolved, the closest <code>package.json</code> to the <code>specifier</code>.</li> </ul> <blockquote> <p><strong>Caveat</strong>: Do not use this to try to determine module format. There are many things affecting that determination; the <code>type</code> field of package.json is the <em>least</em> definitive (ex file extension supersedes it, and a loader hook supersedes that).</p> </blockquote> <blockquote> <p><strong>Caveat</strong>: This currently leverages only the built-in default resolver; if <a href="#synchronous-resolvespecifier-context-nextresolve"><code>resolve</code> customization hooks</a> are registered, they will not affect the resolution. This may change in the future.</p> </blockquote> <pre><code class="language-text">/path/to/project ├ packages/ ├ bar/ ├ bar.js └ package.json // name = '@foo/bar' └ qux/ ├ node_modules/ └ some-package/ └ package.json // name = 'some-package' ├ qux.js └ package.json // name = '@foo/qux' ├ main.js └ package.json // name = '@foo'</code> <button class="copy-button">copy</button></pre> <pre class="with-51-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// /path/to/project/packages/bar/bar.js</span> <span class="hljs-keyword">import</span> { findPackageJSON } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>; <span class="hljs-title function_">findPackageJSON</span>(<span class="hljs-string">'..'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>); <span class="hljs-comment">// '/path/to/project/package.json'</span> <span class="hljs-comment">// Same result when passing an absolute specifier instead:</span> <span class="hljs-title function_">findPackageJSON</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'../'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>)); <span class="hljs-title function_">findPackageJSON</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'../'</span>)); <span class="hljs-title function_">findPackageJSON</span>(<span class="hljs-string">'some-package'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>); <span class="hljs-comment">// '/path/to/project/packages/bar/node_modules/some-package/package.json'</span> <span class="hljs-comment">// When passing an absolute specifier, you might get a different result if the</span> <span class="hljs-comment">// resolved module is inside a subfolder that has nested `package.json`.</span> <span class="hljs-title function_">findPackageJSON</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'some-package'</span>)); <span class="hljs-comment">// '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json'</span> <span class="hljs-title function_">findPackageJSON</span>(<span class="hljs-string">'@foo/qux'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>); <span class="hljs-comment">// '/path/to/project/packages/qux/package.json'</span></code><code class="language-js cjs"><span class="hljs-comment">// /path/to/project/packages/bar/bar.js</span> <span class="hljs-keyword">const</span> { findPackageJSON } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>); <span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>); <span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>); <span class="hljs-title function_">findPackageJSON</span>(<span class="hljs-string">'..'</span>, __filename); <span class="hljs-comment">// '/path/to/project/package.json'</span> <span class="hljs-comment">// Same result when passing an absolute specifier instead:</span> <span class="hljs-title function_">findPackageJSON</span>(<span class="hljs-title function_">pathToFileURL</span>(path.<span class="hljs-title function_">join</span>(__dirname, <span class="hljs-string">'..'</span>))); <span class="hljs-title function_">findPackageJSON</span>(<span class="hljs-string">'some-package'</span>, __filename); <span class="hljs-comment">// '/path/to/project/packages/bar/node_modules/some-package/package.json'</span> <span class="hljs-comment">// When passing an absolute specifier, you might get a different result if the</span> <span class="hljs-comment">// resolved module is inside a subfolder that has nested `package.json`.</span> <span class="hljs-title function_">findPackageJSON</span>(<span class="hljs-title function_">pathToFileURL</span>(<span class="hljs-built_in">require</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'some-package'</span>))); <span class="hljs-comment">// '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json'</span> <span class="hljs-title function_">findPackageJSON</span>(<span class="hljs-string">'@foo/qux'</span>, __filename); <span class="hljs-comment">// '/path/to/project/packages/qux/package.json'</span></code><button class="copy-button">copy</button></pre> </div><div> <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> <div class="api_metadata"> <span>Added in: v18.6.0, v16.17.0</span> </div> <ul> <li><code>moduleName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> name of the module</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type" class="type"><boolean></a> returns true if the module is builtin else returns false</li> </ul> <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>; <span class="hljs-title function_">isBuiltin</span>(<span class="hljs-string">'node:fs'</span>); <span class="hljs-comment">// true</span> <span class="hljs-title function_">isBuiltin</span>(<span class="hljs-string">'fs'</span>); <span class="hljs-comment">// true</span> <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> </div><div> <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> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v24.15.0</td> <td><p><span>Deprecated since: v24.15.0</span></p></td></tr> <tr><td>v23.6.1, v22.13.1, v20.18.2</td> <td><p>Using this feature with the permission model enabled requires passing <code>--allow-worker</code>.</p></td></tr> <tr><td>v20.8.0, v18.19.0</td> <td><p>Add support for WHATWG URL instances.</p></td></tr> <tr><td>v20.6.0, v18.19.0</td> <td><p><span>Added in: v20.6.0, v18.19.0</span></p></td></tr> </tbody></table> </details> </div> <p></p><div class="api_stability api_stability_0"><a href="documentation.html#stability-index">Stability: 0</a> - Deprecated: Use <a href="#moduleregisterhooksoptions"><code>module.registerHooks()</code></a> instead.</div><p></p> <ul> <li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="url.html#the-whatwg-url-api" class="type"><URL></a> Customization hooks to be registered; this should be the same string that would be passed to <code>import()</code>, except that if it is relative, it is resolved relative to <code>parentURL</code>.</li> <li><code>parentURL</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="url.html#the-whatwg-url-api" class="type"><URL></a> If you want to resolve <code>specifier</code> relative to a base URL, such as <code>import.meta.url</code>, you can pass that URL here. <strong>Default:</strong> <code>'data:'</code></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <li><code>parentURL</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="url.html#the-whatwg-url-api" class="type"><URL></a> If you want to resolve <code>specifier</code> relative to a base URL, such as <code>import.meta.url</code>, you can pass that URL here. This property is ignored if the <code>parentURL</code> is supplied as the second argument. <strong>Default:</strong> <code>'data:'</code></li> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Any arbitrary, cloneable JavaScript value to pass into the <a href="#initialize"><code>initialize</code></a> hook.</li> <li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a> <a href="worker_threads.html#portpostmessagevalue-transferlist">transferable objects</a> to be passed into the <code>initialize</code> hook.</li> </ul> </li> </ul> <p>Register a module that exports <a href="#customization-hooks">hooks</a> that customize Node.js module resolution and loading behavior. See <a href="#customization-hooks">Customization hooks</a>.</p> <p>This feature requires <code>--allow-worker</code> if used with the <a href="permissions.html#permission-model">Permission Model</a>.</p> </div><div> <h4><code>module.registerHooks(options)</code><span><a class="mark" href="#moduleregisterhooksoptions" id="moduleregisterhooksoptions">#</a></span><a aria-hidden="true" class="legacy" id="module_module_registerhooks_options"></a></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v24.13.1</td> <td><p>Synchronous and in-thread hooks are now release candidate.</p></td></tr> <tr><td>v23.5.0, v22.15.0</td> <td><p><span>Added in: v23.5.0, v22.15.0</span></p></td></tr> </tbody></table> </details> </div> <p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1.2</a> - Release candidate</div><p></p> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <li><code>load</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> See <a href="#synchronous-loadurl-context-nextload">load hook</a>. <strong>Default:</strong> <code>undefined</code>.</li> <li><code>resolve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> See <a href="#synchronous-resolvespecifier-context-nextresolve">resolve hook</a>. <strong>Default:</strong> <code>undefined</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object with the following property: <ul> <li><code>deregister()</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Remove the registered hooks so that they are no longer called. Hooks are otherwise retained for the lifetime of the running process.</li> </ul> </li> </ul> <p>Register <a href="#customization-hooks">hooks</a> that customize Node.js module resolution and loading behavior. See <a href="#customization-hooks">Customization hooks</a>. The returned object can be used to <a href="#deregistration-of-synchronous-customization-hooks">deregister the hooks</a>.</p> </div><div> <h4><code>module.stripTypeScriptTypes(code[, options])</code><span><a class="mark" href="#modulestriptypescripttypescode-options" id="modulestriptypescripttypescode-options">#</a></span><a aria-hidden="true" class="legacy" id="module_module_striptypescripttypes_code_options"></a></h4> <div class="api_metadata"> <span>Added in: v23.2.0, v22.13.0</span> </div> <p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1.2</a> - Release candidate</div><p></p> <ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> The code to strip type annotations from.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> <strong>Default:</strong> <code>'strip'</code>. Possible values are: <ul> <li><code>'strip'</code> Only strip type annotations without performing the transformation of TypeScript features.</li> <li><code>'transform'</code> Strip type annotations and transform TypeScript features to JavaScript.</li> </ul> </li> <li><code>sourceMap</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code>. Only when <code>mode</code> is <code>'transform'</code>, if <code>true</code>, a source map will be generated for the transformed code.</li> <li><code>sourceUrl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> Specifies the source url used in the source map.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> The code with type annotations stripped.</li> </ul> <p><code>module.stripTypeScriptTypes()</code> removes type annotations from TypeScript code. It can be used to strip type annotations from TypeScript code before running it with <code>vm.runInContext()</code> or <code>vm.compileFunction()</code>.</p> <p>By default, it will throw an error if the code contains TypeScript features that require transformation such as <code>Enums</code>, see <a href="typescript.html#type-stripping">type-stripping</a> for more information.</p> <p>When mode is <code>'transform'</code>, it also transforms TypeScript features to JavaScript, see <a href="typescript.html#typescript-features">transform TypeScript features</a> for more information.</p> <p>When mode is <code>'strip'</code>, source maps are not generated, because locations are preserved. If <code>sourceMap</code> is provided, when mode is <code>'strip'</code>, an error will be thrown.</p> <p><em>WARNING</em>: The output of this function should not be considered stable across Node.js versions, due to changes in the TypeScript parser.</p> <pre class="with-56-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { stripTypeScriptTypes } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>; <span class="hljs-keyword">const</span> code = <span class="hljs-string">'const a: number = 1;'</span>; <span class="hljs-keyword">const</span> strippedCode = <span class="hljs-title function_">stripTypeScriptTypes</span>(code); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(strippedCode); <span class="hljs-comment">// Prints: const a = 1;</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { stripTypeScriptTypes } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>); <span class="hljs-keyword">const</span> code = <span class="hljs-string">'const a: number = 1;'</span>; <span class="hljs-keyword">const</span> strippedCode = <span class="hljs-title function_">stripTypeScriptTypes</span>(code); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(strippedCode); <span class="hljs-comment">// Prints: const a = 1;</span></code><button class="copy-button">copy</button></pre> <p>If <code>sourceUrl</code> is provided, it will be used appended as a comment at the end of the output:</p> <pre class="with-56-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { stripTypeScriptTypes } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>; <span class="hljs-keyword">const</span> code = <span class="hljs-string">'const a: number = 1;'</span>; <span class="hljs-keyword">const</span> strippedCode = <span class="hljs-title function_">stripTypeScriptTypes</span>(code, { <span class="hljs-attr">mode</span>: <span class="hljs-string">'strip'</span>, <span class="hljs-attr">sourceUrl</span>: <span class="hljs-string">'source.ts'</span> }); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(strippedCode); <span class="hljs-comment">// Prints: const a = 1\n\n//# sourceURL=source.ts;</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { stripTypeScriptTypes } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>); <span class="hljs-keyword">const</span> code = <span class="hljs-string">'const a: number = 1;'</span>; <span class="hljs-keyword">const</span> strippedCode = <span class="hljs-title function_">stripTypeScriptTypes</span>(code, { <span class="hljs-attr">mode</span>: <span class="hljs-string">'strip'</span>, <span class="hljs-attr">sourceUrl</span>: <span class="hljs-string">'source.ts'</span> }); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(strippedCode); <span class="hljs-comment">// Prints: const a = 1\n\n//# sourceURL=source.ts;</span></code><button class="copy-button">copy</button></pre> <p>When <code>mode</code> is <code>'transform'</code>, the code is transformed to JavaScript:</p> <pre class="with-56-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { stripTypeScriptTypes } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>; <span class="hljs-keyword">const</span> code = <span class="hljs-string">` namespace MathUtil { export const add = (a: number, b: number) => a + b; }`</span>; <span class="hljs-keyword">const</span> strippedCode = <span class="hljs-title function_">stripTypeScriptTypes</span>(code, { <span class="hljs-attr">mode</span>: <span class="hljs-string">'transform'</span>, <span class="hljs-attr">sourceMap</span>: <span class="hljs-literal">true</span> }); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(strippedCode); <span class="hljs-comment">// Prints:</span> <span class="hljs-comment">// var MathUtil;</span> <span class="hljs-comment">// (function(MathUtil) {</span> <span class="hljs-comment">// MathUtil.add = (a, b)=>a + b;</span> <span class="hljs-comment">// })(MathUtil || (MathUtil = {}));</span> <span class="hljs-comment">// # sourceMappingURL=data:application/json;base64, ...</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { stripTypeScriptTypes } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>); <span class="hljs-keyword">const</span> code = <span class="hljs-string">` namespace MathUtil { export const add = (a: number, b: number) => a + b; }`</span>; <span class="hljs-keyword">const</span> strippedCode = <span class="hljs-title function_">stripTypeScriptTypes</span>(code, { <span class="hljs-attr">mode</span>: <span class="hljs-string">'transform'</span>, <span class="hljs-attr">sourceMap</span>: <span class="hljs-literal">true</span> }); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(strippedCode); <span class="hljs-comment">// Prints:</span> <span class="hljs-comment">// var MathUtil;</span> <span class="hljs-comment">// (function(MathUtil) {</span> <span class="hljs-comment">// MathUtil.add = (a, b)=>a + b;</span> <span class="hljs-comment">// })(MathUtil || (MathUtil = {}));</span> <span class="hljs-comment">// # sourceMappingURL=data:application/json;base64, ...</span></code><button class="copy-button">copy</button></pre> </div><div> <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> <div class="api_metadata"> <span>Added in: v12.12.0</span> </div> <p>The <code>module.syncBuiltinESMExports()</code> method updates all the live bindings for builtin <a href="esm.html">ES Modules</a> to match the properties of the <a href="modules.html">CommonJS</a> exports. It does not add or remove exported names from the <a href="esm.html">ES Modules</a>.</p> <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>); <span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>); <span class="hljs-keyword">const</span> { syncBuiltinESMExports } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>); fs.<span class="hljs-property">readFile</span> = newAPI; <span class="hljs-keyword">delete</span> fs.<span class="hljs-property">readFileSync</span>; <span class="hljs-keyword">function</span> <span class="hljs-title function_">newAPI</span>(<span class="hljs-params"></span>) { <span class="hljs-comment">// ...</span> } fs.<span class="hljs-property">newAPI</span> = newAPI; <span class="hljs-title function_">syncBuiltinESMExports</span>(); <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> { <span class="hljs-comment">// It syncs the existing readFile property with the new value</span> assert.<span class="hljs-title function_">strictEqual</span>(esmFS.<span class="hljs-property">readFile</span>, newAPI); <span class="hljs-comment">// readFileSync has been deleted from the required fs</span> 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>); <span class="hljs-comment">// syncBuiltinESMExports() does not remove readFileSync from esmFS</span> 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>); <span class="hljs-comment">// syncBuiltinESMExports() does not add names</span> assert.<span class="hljs-title function_">strictEqual</span>(esmFS.<span class="hljs-property">newAPI</span>, <span class="hljs-literal">undefined</span>); });</code> <button class="copy-button">copy</button></pre> </div> </section><section><h3>Module compile cache<span><a class="mark" href="#module-compile-cache" id="module-compile-cache">#</a></span><a aria-hidden="true" class="legacy" id="module_module_compile_cache"></a></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v22.8.0</td> <td><p>add initial JavaScript APIs for runtime access.</p></td></tr> <tr><td>v22.1.0</td> <td><p><span>Added in: v22.1.0</span></p></td></tr> </tbody></table> </details> </div> <p>The module compile cache can be enabled either using the <a href="#moduleenablecompilecacheoptions"><code>module.enableCompileCache()</code></a> method or the <a href="cli.html#node_compile_cachedir"><code>NODE_COMPILE_CACHE=dir</code></a> environment variable. After it is enabled, whenever Node.js compiles a CommonJS, a ECMAScript Module, or a TypeScript module, it will use on-disk <a href="https://v8.dev/blog/code-caching-for-devs">V8 code cache</a> persisted in the specified directory to speed up the compilation. This may slow down the first load of a module graph, but subsequent loads of the same module graph may get a significant speedup if the contents of the modules do not change.</p> <p>To clean up the generated compile cache on disk, simply remove the cache directory. The cache directory will be recreated the next time the same directory is used for for compile cache storage. To avoid filling up the disk with stale cache, it is recommended to use a directory under the <a href="os.html#ostmpdir"><code>os.tmpdir()</code></a>. If the compile cache is enabled by a call to <a href="#moduleenablecompilecacheoptions"><code>module.enableCompileCache()</code></a> without specifying the <code>directory</code>, Node.js will use the <a href="cli.html#node_compile_cachedir"><code>NODE_COMPILE_CACHE=dir</code></a> environment variable if it's set, or defaults to <code>path.join(os.tmpdir(), 'node-compile-cache')</code> otherwise. To locate the compile cache directory used by a running Node.js instance, use <a href="#modulegetcompilecachedir"><code>module.getCompileCacheDir()</code></a>.</p> <p>The enabled module compile cache can be disabled by the <a href="cli.html#node_disable_compile_cache1"><code>NODE_DISABLE_COMPILE_CACHE=1</code></a> environment variable. This can be useful when the compile cache leads to unexpected or undesired behaviors (e.g. less precise test coverage).</p> <p>At the moment, when the compile cache is enabled and a module is loaded afresh, the code cache is generated from the compiled code immediately, but will only be written to disk when the Node.js instance is about to exit. This is subject to change. The <a href="#moduleflushcompilecache"><code>module.flushCompileCache()</code></a> method can be used to ensure the accumulated code cache is flushed to disk in case the application wants to spawn other Node.js instances and let them share the cache long before the parent exits.</p> <p>The compile cache layout on disk is an implementation detail and should not be relied upon. The compile cache generated is typically only reusable in the same version of Node.js, and should be not assumed to be compatible across different versions of Node.js.</p> <div> <h4>Portability of the compile cache<span><a class="mark" href="#portability-of-the-compile-cache" id="portability-of-the-compile-cache">#</a></span><a aria-hidden="true" class="legacy" id="module_portability_of_the_compile_cache"></a></h4> <p>By default, caches are invalidated when the absolute paths of the modules being cached are changed. To keep the cache working after moving the project directory, enable portable compile cache. This allows previously compiled modules to be reused across different directory locations as long as the layout relative to the cache directory remains the same. This would be done on a best-effort basis. If Node.js cannot compute the location of a module relative to the cache directory, the module will not be cached.</p> <p>There are two ways to enable the portable mode:</p> <ol> <li> <p>Using the portable option in <a href="#moduleenablecompilecacheoptions"><code>module.enableCompileCache()</code></a>:</p> <pre><code class="language-js"><span class="hljs-comment">// Non-portable cache (default): cache breaks if project is moved</span> <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">enableCompileCache</span>({ <span class="hljs-attr">directory</span>: <span class="hljs-string">'/path/to/cache/storage/dir'</span> }); <span class="hljs-comment">// Portable cache: cache works after the project is moved</span> <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">enableCompileCache</span>({ <span class="hljs-attr">directory</span>: <span class="hljs-string">'/path/to/cache/storage/dir'</span>, <span class="hljs-attr">portable</span>: <span class="hljs-literal">true</span> });</code> <button class="copy-button">copy</button></pre> </li> <li> <p>Setting the environment variable: <a href="cli.html#node_compile_cache_portable1"><code>NODE_COMPILE_CACHE_PORTABLE=1</code></a></p> </li> </ol> </div><div> <h4>Limitations of the compile cache<span><a class="mark" href="#limitations-of-the-compile-cache" id="limitations-of-the-compile-cache">#</a></span><a aria-hidden="true" class="legacy" id="module_limitations_of_the_compile_cache"></a></h4> <p>Currently when using the compile cache with <a href="https://v8project.blogspot.com/2017/12/javascript-code-coverage.html">V8 JavaScript code coverage</a>, the coverage being collected by V8 may be less precise in functions that are deserialized from the code cache. It's recommended to turn this off when running tests to generate precise coverage.</p> <p>Compilation cache generated by one version of Node.js can not be reused by a different version of Node.js. Cache generated by different versions of Node.js will be stored separately if the same base directory is used to persist the cache, so they can co-exist.</p> </div><div> <h4><code>module.constants.compileCacheStatus</code><span><a class="mark" href="#moduleconstantscompilecachestatus" id="moduleconstantscompilecachestatus">#</a></span><a aria-hidden="true" class="legacy" id="module_module_constants_compilecachestatus"></a></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v24.15.0</td> <td><p>This feature is no longer experimental.</p></td></tr> <tr><td>v22.8.0</td> <td><p><span>Added in: v22.8.0</span></p></td></tr> </tbody></table> </details> </div> <p>The following constants are returned as the <code>status</code> field in the object returned by <a href="#moduleenablecompilecacheoptions"><code>module.enableCompileCache()</code></a> to indicate the result of the attempt to enable the <a href="#module-compile-cache">module compile cache</a>.</p> <table> <tbody><tr> <th>Constant</th> <th>Description</th> </tr> <tr> <td><code>ENABLED</code></td> <td> Node.js has enabled the compile cache successfully. The directory used to store the compile cache will be returned in the <code>directory</code> field in the returned object. </td> </tr> <tr> <td><code>ALREADY_ENABLED</code></td> <td> The compile cache has already been enabled before, either by a previous call to <code>module.enableCompileCache()</code>, or by the <code>NODE_COMPILE_CACHE=dir</code> environment variable. The directory used to store the compile cache will be returned in the <code>directory</code> field in the returned object. </td> </tr> <tr> <td><code>FAILED</code></td> <td> Node.js fails to enable the compile cache. This can be caused by the lack of permission to use the specified directory, or various kinds of file system errors. The detail of the failure will be returned in the <code>message</code> field in the returned object. </td> </tr> <tr> <td><code>DISABLED</code></td> <td> Node.js cannot enable the compile cache because the environment variable <code>NODE_DISABLE_COMPILE_CACHE=1</code> has been set. </td> </tr> </tbody></table> </div><div> <h4><code>module.enableCompileCache([options])</code><span><a class="mark" href="#moduleenablecompilecacheoptions" id="moduleenablecompilecacheoptions">#</a></span><a aria-hidden="true" class="legacy" id="module_module_enablecompilecache_options"></a></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v24.15.0</td> <td><p>This feature is no longer experimental.</p></td></tr> <tr><td>v24.12.0</td> <td><p>Add <code>portable</code> option to enable portable compile cache.</p></td></tr> <tr><td>v24.12.0</td> <td><p>Rename the unreleased <code>path</code> option to <code>directory</code> to maintain consistency.</p></td></tr> <tr><td>v22.8.0</td> <td><p><span>Added in: v22.8.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Optional. If a string is passed, it is considered to be <code>options.directory</code>. <ul> <li><code>directory</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> Optional. Directory to store the compile cache. If not specified, the directory specified by the <a href="cli.html#node_compile_cachedir"><code>NODE_COMPILE_CACHE=dir</code></a> environment variable will be used if it's set, or <code>path.join(os.tmpdir(), 'node-compile-cache')</code> otherwise.</li> <li><code>portable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type" class="type"><boolean></a> Optional. If <code>true</code>, enables portable compile cache so that the cache can be reused even if the project directory is moved. This is a best-effort feature. If not specified, it will depend on whether the environment variable <a href="cli.html#node_compile_cache_portable1"><code>NODE_COMPILE_CACHE_PORTABLE=1</code></a> is set.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <li><code>status</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type" class="type"><integer></a> One of the <a href="#moduleconstantscompilecachestatus"><code>module.constants.compileCacheStatus</code></a></li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> If Node.js cannot enable the compile cache, this contains the error message. Only set if <code>status</code> is <code>module.constants.compileCacheStatus.FAILED</code>.</li> <li><code>directory</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> If the compile cache is enabled, this contains the directory where the compile cache is stored. Only set if <code>status</code> is <code>module.constants.compileCacheStatus.ENABLED</code> or <code>module.constants.compileCacheStatus.ALREADY_ENABLED</code>.</li> </ul> </li> </ul> <p>Enable <a href="#module-compile-cache">module compile cache</a> in the current Node.js instance.</p> <p>For general use cases, it's recommended to call <code>module.enableCompileCache()</code> without specifying the <code>options.directory</code>, so that the directory can be overridden by the <code>NODE_COMPILE_CACHE</code> environment variable when necessary.</p> <p>Since compile cache is supposed to be a optimization that is not mission critical, this method is designed to not throw any exception when the compile cache cannot be enabled. Instead, it will return an object containing an error message in the <code>message</code> field to aid debugging. If compile cache is enabled successfully, the <code>directory</code> field in the returned object contains the path to the directory where the compile cache is stored. The <code>status</code> field in the returned object would be one of the <code>module.constants.compileCacheStatus</code> values to indicate the result of the attempt to enable the <a href="#module-compile-cache">module compile cache</a>.</p> <p>This method only affects the current Node.js instance. To enable it in child worker threads, either call this method in child worker threads too, or set the <code>process.env.NODE_COMPILE_CACHE</code> value to compile cache directory so the behavior can be inherited into the child workers. The directory can be obtained either from the <code>directory</code> field returned by this method, or with <a href="#modulegetcompilecachedir"><code>module.getCompileCacheDir()</code></a>.</p> </div><div> <h4><code>module.flushCompileCache()</code><span><a class="mark" href="#moduleflushcompilecache" id="moduleflushcompilecache">#</a></span><a aria-hidden="true" class="legacy" id="module_module_flushcompilecache"></a></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v24.15.0</td> <td><p>This feature is no longer experimental.</p></td></tr> <tr><td>v23.0.0, v22.10.0</td> <td><p><span>Added in: v23.0.0, v22.10.0</span></p></td></tr> </tbody></table> </details> </div> <p>Flush the <a href="#module-compile-cache">module compile cache</a> accumulated from modules already loaded in the current Node.js instance to disk. This returns after all the flushing file system operations come to an end, no matter they succeed or not. If there are any errors, this will fail silently, since compile cache misses should not interfere with the actual operation of the application.</p> </div><div> <h4><code>module.getCompileCacheDir()</code><span><a class="mark" href="#modulegetcompilecachedir" id="modulegetcompilecachedir">#</a></span><a aria-hidden="true" class="legacy" id="module_module_getcompilecachedir"></a></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v24.15.0</td> <td><p>This feature is no longer experimental.</p></td></tr> <tr><td>v22.8.0</td> <td><p><span>Added in: v22.8.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> Path to the <a href="#module-compile-cache">module compile cache</a> directory if it is enabled, or <code>undefined</code> otherwise.</li> </ul> <p><i id="module_customization_hooks"></i></p> </div> </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> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v24.13.1</td> <td><p>Synchronous and in-thread hooks are now release candidate.</p></td></tr> <tr><td>v23.5.0, v22.15.0</td> <td><p>Add support for synchronous and in-thread hooks.</p></td></tr> <tr><td>v20.6.0, v18.19.0</td> <td><p>Added <code>initialize</code> hook to replace <code>globalPreload</code>.</p></td></tr> <tr><td>v18.6.0, v16.17.0</td> <td><p>Add support for chaining loaders.</p></td></tr> <tr><td>v16.12.0</td> <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> <tr><td>v8.8.0</td> <td><p><span>Added in: v8.8.0</span></p></td></tr> </tbody></table> </details> </div> <p>Node.js currently supports two types of module customization hooks:</p> <ol> <li><a href="#moduleregisterhooksoptions"><code>module.registerHooks(options)</code></a>: takes synchronous hook functions that are run directly on the thread where the modules are loaded.</li> <li><a href="#moduleregisterspecifier-parenturl-options"><code>module.register(specifier[, parentURL][, options])</code></a>: takes specifier to a module that exports asynchronous hook functions. The functions are run on a separate loader thread.</li> </ol> <p>The asynchronous hooks incur extra overhead from inter-thread communication, and have <a href="#caveats-of-asynchronous-customization-hooks">several caveats</a> especially when customizing CommonJS modules in the module graph. In most cases, it's recommended to use synchronous hooks via <code>module.registerHooks()</code> for simplicity.</p> <div> <h4>Synchronous customization hooks<span><a class="mark" href="#synchronous-customization-hooks" id="synchronous-customization-hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_synchronous_customization_hooks"></a></h4> <p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1.2</a> - Release candidate</div><p></p> <p><i id="enabling_module_customization_hooks"></i></p> <div> <h5>Registration of synchronous customization hooks<span><a class="mark" href="#registration-of-synchronous-customization-hooks" id="registration-of-synchronous-customization-hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_registration_of_synchronous_customization_hooks"></a></h5> <p>To register synchronous customization hooks, use <a href="#moduleregisterhooksoptions"><code>module.registerHooks()</code></a>, which takes <a href="#hook-functions-accepted-by-moduleregisterhooks">synchronous hook functions</a> directly in-line.</p> <pre class="with-49-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// register-hooks.js</span> <span class="hljs-keyword">import</span> { registerHooks } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>; <span class="hljs-title function_">registerHooks</span>({ <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) { <span class="hljs-comment">/* implementation */</span> }, <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) { <span class="hljs-comment">/* implementation */</span> }, });</code><code class="language-js cjs"><span class="hljs-comment">// register-hooks.js</span> <span class="hljs-keyword">const</span> { registerHooks } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>); <span class="hljs-title function_">registerHooks</span>({ <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) { <span class="hljs-comment">/* implementation */</span> }, <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) { <span class="hljs-comment">/* implementation */</span> }, });</code><button class="copy-button">copy</button></pre> <div> <h6>Registering hooks before application code runs with flags<span><a class="mark" href="#registering-hooks-before-application-code-runs-with-flags" id="registering-hooks-before-application-code-runs-with-flags">#</a></span><a aria-hidden="true" class="legacy" id="module_registering_hooks_before_application_code_runs_with_flags"></a></h6> <p>The hooks can be registered before the application code is run by using the <a href="cli.html#--importmodule"><code>--import</code></a> or <a href="cli.html#-r---require-module"><code>--require</code></a> flag:</p> <pre><code class="language-bash">node --import ./register-hooks.js ./my-app.js node --require ./register-hooks.js ./my-app.js</code> <button class="copy-button">copy</button></pre> <p>The specifier passed to <code>--import</code> or <code>--require</code> can also come from a package:</p> <pre><code class="language-bash">node --import some-package/register ./my-app.js node --require some-package/register ./my-app.js</code> <button class="copy-button">copy</button></pre> <p>Where <code>some-package</code> has an <a href="packages.html#exports"><code>"exports"</code></a> field defining the <code>/register</code> export to map to a file that calls <code>registerHooks()</code>, like the <code>register-hooks.js</code> examples above.</p> <p>Using <code>--import</code> or <code>--require</code> ensures that the hooks are registered before any application code is loaded, including the entry point of the application and for any worker threads by default as well.</p> </div><div> <h6>Registering hooks before application code runs programmatically<span><a class="mark" href="#registering-hooks-before-application-code-runs-programmatically" id="registering-hooks-before-application-code-runs-programmatically">#</a></span><a aria-hidden="true" class="legacy" id="module_registering_hooks_before_application_code_runs_programmatically"></a></h6> <p>Alternatively, <code>registerHooks()</code> can be called from the entry point.</p> <p>If the entry point needs to load other modules and the loading process needs to be customized, load them using either <code>require()</code> or dynamic <code>import()</code> after the hooks are registered. Do not use static <code>import</code> statements to load modules that need to be customized in the same module that registers the hooks, because static <code>import</code> statements are evaluated before any code in the importer module is run, including the call to <code>registerHooks()</code>, regardless of where the static <code>import</code> statements appear in the importer module.</p> <pre class="with-49-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { registerHooks } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>; <span class="hljs-title function_">registerHooks</span>({ <span class="hljs-comment">/* implementation of synchronous hooks */</span> }); <span class="hljs-comment">// If loaded using static import, the hooks would not be applied when loading</span> <span class="hljs-comment">// my-app.mjs, because statically imported modules are all executed before its</span> <span class="hljs-comment">// importer regardless of where the static import appears.</span> <span class="hljs-comment">// import './my-app.mjs';</span> <span class="hljs-comment">// my-app.mjs must be loaded dynamically to ensure the hooks are applied.</span> <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-keyword">const</span> { registerHooks } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>); <span class="hljs-title function_">registerHooks</span>({ <span class="hljs-comment">/* implementation of synchronous hooks */</span> }); <span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.mjs'</span>); <span class="hljs-comment">// Or, if my-app.mjs does not have top-level await or it's a CommonJS module,</span> <span class="hljs-comment">// require() can also be used:</span> <span class="hljs-comment">// require('./my-app.mjs');</span></code><button class="copy-button">copy</button></pre> </div><div> <h6>Registering hooks before application code runs with a <code>data:</code> URL<span><a class="mark" href="#registering-hooks-before-application-code-runs-with-a-data-url" id="registering-hooks-before-application-code-runs-with-a-data-url">#</a></span><a aria-hidden="true" class="legacy" id="module_registering_hooks_before_application_code_runs_with_a_data_url"></a></h6> <p>Alternatively, inline JavaScript code can be embedded in <code>data:</code> URLs to register the hooks before the application code runs. For example,</p> <pre><code class="language-bash">node --import <span class="hljs-string">'data:text/javascript,import {registerHooks} from "node:module"; registerHooks(/* hooks code */);'</span> ./my-app.js</code> <button class="copy-button">copy</button></pre> </div></div><div> <h5>Convention of hooks and chaining<span><a class="mark" href="#convention-of-hooks-and-chaining" id="convention-of-hooks-and-chaining">#</a></span><a aria-hidden="true" class="legacy" id="module_convention_of_hooks_and_chaining"></a></h5> <p>Hooks are part of a chain, even if that chain consists of only one custom (user-provided) hook and the default hook, which is always present.</p> <p>Hook functions nest: each one must always return a plain object, and chaining happens as a result of each function calling <code>next<hookName>()</code>, which is a reference to the subsequent loader's hook (in LIFO order).</p> <p>It's possible to call <code>registerHooks()</code> more than once:</p> <pre class="with-49-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// entrypoint.mjs</span> <span class="hljs-keyword">import</span> { registerHooks } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>; <span class="hljs-keyword">const</span> hook1 = { <span class="hljs-comment">/* implementation of hooks */</span> }; <span class="hljs-keyword">const</span> hook2 = { <span class="hljs-comment">/* implementation of hooks */</span> }; <span class="hljs-comment">// hook2 runs before hook1.</span> <span class="hljs-title function_">registerHooks</span>(hook1); <span class="hljs-title function_">registerHooks</span>(hook2);</code><code class="language-js cjs"><span class="hljs-comment">// entrypoint.cjs</span> <span class="hljs-keyword">const</span> { registerHooks } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>); <span class="hljs-keyword">const</span> hook1 = { <span class="hljs-comment">/* implementation of hooks */</span> }; <span class="hljs-keyword">const</span> hook2 = { <span class="hljs-comment">/* implementation of hooks */</span> }; <span class="hljs-comment">// hook2 runs before hook1.</span> <span class="hljs-title function_">registerHooks</span>(hook1); <span class="hljs-title function_">registerHooks</span>(hook2);</code><button class="copy-button">copy</button></pre> <p>In this example, the registered hooks will form chains. These chains run last-in, first-out (LIFO). If both <code>hook1</code> and <code>hook2</code> define a <code>resolve</code> hook, they will be called like so (note the right-to-left, starting with <code>hook2.resolve</code>, then <code>hook1.resolve</code>, then the Node.js default):</p> <p>Node.js default <code>resolve</code> ← <code>hook1.resolve</code> ← <code>hook2.resolve</code></p> <p>The same applies to all the other hooks.</p> <p>A hook that returns a value lacking a required property triggers an exception. A hook that returns without calling <code>next<hookName>()</code> <em>and</em> without returning <code>shortCircuit: true</code> also triggers an exception. These errors are to help prevent unintentional breaks in the chain. Return <code>shortCircuit: true</code> from a hook to signal that the chain is intentionally ending at your hook.</p> <p>If a hook should be applied when loading other hook modules, the other hook modules should be loaded after the hook is registered.</p> </div><div> <h5>Deregistration of synchronous customization hooks<span><a class="mark" href="#deregistration-of-synchronous-customization-hooks" id="deregistration-of-synchronous-customization-hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_deregistration_of_synchronous_customization_hooks"></a></h5> <p>The object returned by <code>registerHooks()</code> has a <code>deregister()</code> method that can be used to remove the hooks from the chain. Once <code>deregister()</code> is called, the hooks will no longer be invoked during module resolution or loading.</p> <p>This is currently only available for synchronous hooks registered via <code>registerHooks()</code>, not for asynchronous hooks registered via <code>module.register()</code>.</p> <pre class="with-49-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { registerHooks } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>; <span class="hljs-keyword">const</span> hooks = <span class="hljs-title function_">registerHooks</span>({ <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'resolve hook called for'</span>, specifier); <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier, context); }, <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) { <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url, context); }, }); <span class="hljs-comment">// At this point, the hooks are active and will be called for</span> <span class="hljs-comment">// any subsequent import() or require() calls.</span> <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-module.mjs'</span>); <span class="hljs-comment">// Later, remove the hooks from the chain.</span> hooks.<span class="hljs-title function_">deregister</span>(); <span class="hljs-comment">// Subsequent loads will no longer trigger the hooks.</span> <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./another-module.mjs'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { registerHooks } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>); <span class="hljs-keyword">const</span> hooks = <span class="hljs-title function_">registerHooks</span>({ <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'resolve hook called for'</span>, specifier); <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier, context); }, <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) { <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url, context); }, }); <span class="hljs-comment">// At this point, the hooks are active and will be called for</span> <span class="hljs-comment">// any subsequent require() calls.</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'./my-module.cjs'</span>); <span class="hljs-comment">// Later, remove the hooks from the chain.</span> hooks.<span class="hljs-title function_">deregister</span>(); <span class="hljs-comment">// Subsequent loads will no longer trigger the hooks.</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'./another-module.cjs'</span>);</code><button class="copy-button">copy</button></pre> </div><div> <h5>Hook functions accepted by <code>module.registerHooks()</code><span><a class="mark" href="#hook-functions-accepted-by-moduleregisterhooks" id="hook-functions-accepted-by-moduleregisterhooks">#</a></span><a aria-hidden="true" class="legacy" id="module_hook_functions_accepted_by_module_registerhooks"></a></h5> <div class="api_metadata"> <span>Added in: v23.5.0, v22.15.0</span> </div> <p>The <code>module.registerHooks()</code> method accepts the following synchronous hook functions.</p> <pre><code class="language-js mjs"><span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) { <span class="hljs-comment">// Take an `import` or `require` specifier and resolve it to a URL.</span> } <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) { <span class="hljs-comment">// Take a resolved URL and return the source code to be evaluated.</span> }</code> <button class="copy-button">copy</button></pre> <p>Synchronous hooks are run in the same thread and the same <a href="https://tc39.es/ecma262/#realm">realm</a> where the modules are loaded, the code in the hook function can pass values to the modules being referenced directly via global variables or other shared states.</p> <p>Unlike the asynchronous hooks, the synchronous hooks are not inherited into child worker threads by default, though if the hooks are registered using a file preloaded by <a href="cli.html#--importmodule"><code>--import</code></a> or <a href="cli.html#-r---require-module"><code>--require</code></a>, child worker threads can inherit the preloaded scripts via <code>process.execArgv</code> inheritance. See <a href="worker_threads.html#new-workerfilename-options">the documentation of <code>Worker</code></a> for details.</p> </div><div> <h5>Synchronous <code>resolve(specifier, context, nextResolve)</code><span><a class="mark" href="#synchronous-resolvespecifier-context-nextresolve" id="synchronous-resolvespecifier-context-nextresolve">#</a></span><a aria-hidden="true" class="legacy" id="module_synchronous_resolve_specifier_context_nextresolve"></a></h5> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v23.5.0, v22.15.0</td> <td><p>Add support for synchronous and in-thread hooks.</p></td></tr> </tbody></table> </details> </div> <ul> <li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a></li> <li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <li><code>conditions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string[]></a> Export conditions of the relevant <code>package.json</code></li> <li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object whose key-value pairs represent the attributes for the module to import</li> <li><code>parentURL</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> The module importing this one, or undefined if this is the Node.js entry point</li> </ul> </li> <li><code>nextResolve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The subsequent <code>resolve</code> hook in the chain, or the Node.js default <code>resolve</code> hook after the last user-supplied <code>resolve</code> hook <ul> <li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a></li> <li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> When omitted, the defaults are provided. When provided, defaults are merged in with preference to the provided properties.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type" class="type"><null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> A hint to the <code>load</code> hook (it might be ignored). It can be a module format (such as <code>'commonjs'</code> or <code>'module'</code>) or an arbitrary value like <code>'css'</code> or <code>'yaml'</code>.</li> <li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> The import attributes to use when caching the module (optional; if excluded the input will be used)</li> <li><code>shortCircuit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type" class="type"><boolean></a> A signal that this hook intends to terminate the chain of <code>resolve</code> hooks. <strong>Default:</strong> <code>false</code></li> <li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> The absolute URL to which this input resolves</li> </ul> </li> </ul> <p>The <code>resolve</code> hook chain is responsible for telling Node.js where to find and how to cache a given <code>import</code> statement or expression, or <code>require</code> call. It can optionally return a format (such as <code>'module'</code>) as a hint to the <code>load</code> hook. If a format is specified, the <code>load</code> hook is ultimately responsible for providing the final <code>format</code> value (and it is free to ignore the hint provided by <code>resolve</code>); if <code>resolve</code> provides a <code>format</code>, a custom <code>load</code> hook is required even if only to pass the value to the Node.js default <code>load</code> hook.</p> <p>Import type attributes are part of the cache key for saving loaded modules into the internal module cache. The <code>resolve</code> hook is responsible for returning an <code>importAttributes</code> object if the module should be cached with different attributes than were present in the source code.</p> <p>The <code>conditions</code> property in <code>context</code> is an array of conditions that will be used to match <a href="packages.html#conditional-exports">package exports conditions</a> for this resolution request. They can be used for looking up conditional mappings elsewhere or to modify the list when calling the default resolution logic.</p> <p>The current <a href="packages.html#conditional-exports">package exports conditions</a> are always in the <code>context.conditions</code> array passed into the hook. To guarantee <em>default Node.js module specifier resolution behavior</em> when calling <code>defaultResolve</code>, the <code>context.conditions</code> array passed to it <em>must</em> include <em>all</em> elements of the <code>context.conditions</code> array originally passed into the <code>resolve</code> hook.</p> <pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { registerHooks } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>; <span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) { <span class="hljs-comment">// When calling `defaultResolve`, the arguments can be modified. For example,</span> <span class="hljs-comment">// to change the specifier or to add applicable export conditions.</span> <span class="hljs-keyword">if</span> (specifier.<span class="hljs-title function_">includes</span>(<span class="hljs-string">'foo'</span>)) { specifier = specifier.<span class="hljs-title function_">replace</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>); <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier, { ...context, <span class="hljs-attr">conditions</span>: [...context.<span class="hljs-property">conditions</span>, <span class="hljs-string">'another-condition'</span>], }); } <span class="hljs-comment">// The hook can also skip default resolution and provide a custom URL.</span> <span class="hljs-keyword">if</span> (specifier === <span class="hljs-string">'special-module'</span>) { <span class="hljs-keyword">return</span> { <span class="hljs-attr">url</span>: <span class="hljs-string">'file:///path/to/special-module.mjs'</span>, <span class="hljs-attr">format</span>: <span class="hljs-string">'module'</span>, <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">// This is mandatory if nextResolve() is not called.</span> }; } <span class="hljs-comment">// If no customization is needed, defer to the next hook in the chain which would be the</span> <span class="hljs-comment">// Node.js default resolve if this is the last user-specified loader.</span> <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier); } <span class="hljs-title function_">registerHooks</span>({ resolve });</code> <button class="copy-button">copy</button></pre> </div><div> <h5>Synchronous <code>load(url, context, nextLoad)</code><span><a class="mark" href="#synchronous-loadurl-context-nextload" id="synchronous-loadurl-context-nextload">#</a></span><a aria-hidden="true" class="legacy" id="module_synchronous_load_url_context_nextload"></a></h5> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v23.5.0, v22.15.0</td> <td><p>Add support for synchronous and in-thread version.</p></td></tr> </tbody></table> </details> </div> <ul> <li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> The URL returned by the <code>resolve</code> chain</li> <li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <li><code>conditions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string[]></a> Export conditions of the relevant <code>package.json</code></li> <li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type" class="type"><null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> The format optionally supplied by the <code>resolve</code> hook chain. This can be any string value as an input; input values do not need to conform to the list of acceptable return values described below.</li> <li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> </li> <li><code>nextLoad</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The subsequent <code>load</code> hook in the chain, or the Node.js default <code>load</code> hook after the last user-supplied <code>load</code> hook <ul> <li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a></li> <li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> When omitted, defaults are provided. When provided, defaults are merged in with preference to the provided properties. In the default <code>nextLoad</code>, if the module pointed to by <code>url</code> does not have explicit module type information, <code>context.format</code> is mandatory. <!-- TODO(joyeecheung): make it at least optionally non-mandatory by allowing JS-style/TS-style module detection when the format is simply unknown --> </li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> One of the acceptable module formats listed <a href="#accepted-final-formats-returned-by-load">below</a>.</li> <li><code>shortCircuit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type" class="type"><boolean></a> A signal that this hook intends to terminate the chain of <code>load</code> hooks. <strong>Default:</strong> <code>false</code></li> <li><code>source</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> The source for Node.js to evaluate</li> </ul> </li> </ul> <p>The <code>load</code> hook provides a way to define a custom method for retrieving the source code of a resolved URL. This would allow a loader to potentially avoid reading files from disk. It could also be used to map an unrecognized format to a supported one, for example <code>yaml</code> to <code>module</code>.</p> <pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { registerHooks } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>; <span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>; <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) { <span class="hljs-comment">// The hook can skip default loading and provide a custom source code.</span> <span class="hljs-keyword">if</span> (url === <span class="hljs-string">'special-module'</span>) { <span class="hljs-keyword">return</span> { <span class="hljs-attr">source</span>: <span class="hljs-string">'export const special = 42;'</span>, <span class="hljs-attr">format</span>: <span class="hljs-string">'module'</span>, <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">// This is mandatory if nextLoad() is not called.</span> }; } <span class="hljs-comment">// It's possible to modify the source code loaded by the next - possibly default - step,</span> <span class="hljs-comment">// for example, replacing 'foo' with 'bar' in the source code of the module.</span> <span class="hljs-keyword">const</span> result = <span class="hljs-title function_">nextLoad</span>(url, context); <span class="hljs-keyword">const</span> source = <span class="hljs-keyword">typeof</span> result.<span class="hljs-property">source</span> === <span class="hljs-string">'string'</span> ? result.<span class="hljs-property">source</span> : <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(result.<span class="hljs-property">source</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>); <span class="hljs-keyword">return</span> { <span class="hljs-attr">source</span>: source.<span class="hljs-title function_">replace</span>(<span class="hljs-regexp">/foo/g</span>, <span class="hljs-string">'bar'</span>), ...result, }; } <span class="hljs-title function_">registerHooks</span>({ resolve });</code> <button class="copy-button">copy</button></pre> <p>In a more advanced scenario, this can also be used to transform an unsupported source to a supported one (see <a href="#examples">Examples</a> below).</p> <div> <h6>Accepted final formats returned by <code>load</code><span><a class="mark" href="#accepted-final-formats-returned-by-load" id="accepted-final-formats-returned-by-load">#</a></span><a aria-hidden="true" class="legacy" id="module_accepted_final_formats_returned_by_load"></a></h6> <p>The final value of <code>format</code> must be one of the following:</p> <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>'addon'</code></td><td>Load a Node.js addon</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type" class="type"><null></a></td></tr><tr><td><code>'builtin'</code></td><td>Load a Node.js builtin module</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type" class="type"><null></a></td></tr><tr><td><code>'commonjs-typescript'</code></td><td>Load a Node.js CommonJS module with TypeScript syntax</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type" class="type"><null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a></td></tr><tr><td><code>'commonjs'</code></td><td>Load a Node.js CommonJS module</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type" class="type"><null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a></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/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a></td></tr><tr><td><code>'module-typescript'</code></td><td>Load an ES module with TypeScript syntax</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></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/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></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" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a></td></tr></tbody></table> <p>The value of <code>source</code> is ignored for format <code>'builtin'</code> because currently it is not possible to replace the value of a Node.js builtin (core) module.</p> <blockquote> <p>These types all correspond to classes defined in ECMAScript.</p> </blockquote> <ul> <li>The specific <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> object is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a>.</li> <li>The specific <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> object is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a>.</li> </ul> <p>If the source value of a text-based format (i.e., <code>'json'</code>, <code>'module'</code>) is not a string, it is converted to a string using <a href="util.html#class-utiltextdecoder"><code>util.TextDecoder</code></a>.</p> </div></div></div><div> <h4>Asynchronous customization hooks<span><a class="mark" href="#asynchronous-customization-hooks" id="asynchronous-customization-hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_asynchronous_customization_hooks"></a></h4> <p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1.1</a> - Active Development</div><p></p> <div> <h5>Caveats of asynchronous customization hooks<span><a class="mark" href="#caveats-of-asynchronous-customization-hooks" id="caveats-of-asynchronous-customization-hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_caveats_of_asynchronous_customization_hooks"></a></h5> <p>The asynchronous customization hooks have many caveats and it is uncertain if their issues can be resolved. Users are encouraged to use the synchronous customization hooks via <code>module.registerHooks()</code> instead to avoid these caveats.</p> <ul> <li>Asynchronous hooks run on a separate thread, so the hook functions cannot directly mutate the global state of the modules being customized. It's typical to use message channels and atomics to pass data between the two or to affect control flows. See <a href="#communication-with-asynchronous-module-customization-hooks">Communication with asynchronous module customization hooks</a>.</li> <li>Asynchronous hooks do not affect all <code>require()</code> calls in the module graph. <ul> <li>Custom <code>require</code> functions created using <code>module.createRequire()</code> are not affected.</li> <li>If the asynchronous <code>load</code> hook does not override the <code>source</code> for CommonJS modules that go through it, the child modules loaded by those CommonJS modules via built-in <code>require()</code> would not be affected by the asynchronous hooks either.</li> </ul> </li> <li>There are several caveats that the asynchronous hooks need to handle when customizing CommonJS modules. See <a href="#asynchronous-resolvespecifier-context-nextresolve">asynchronous <code>resolve</code> hook</a> and <a href="#asynchronous-loadurl-context-nextload">asynchronous <code>load</code> hook</a> for details.</li> <li>When <code>require()</code> calls inside CommonJS modules are customized by asynchronous hooks, Node.js may need to load the source code of the CommonJS module multiple times to maintain compatibility with existing CommonJS monkey-patching. If the module code changes between loads, this may lead to unexpected behaviors. <ul> <li>As a side effect, if both asynchronous hooks and synchronous hooks are registered and the asynchronous hooks choose to customize the CommonJS module, the synchronous hooks may be invoked multiple times for the <code>require()</code> calls in that CommonJS module.</li> </ul> </li> </ul> </div><div> <h5>Registration of asynchronous customization hooks<span><a class="mark" href="#registration-of-asynchronous-customization-hooks" id="registration-of-asynchronous-customization-hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_registration_of_asynchronous_customization_hooks"></a></h5> <p>Asynchronous customization hooks are registered using <a href="#moduleregisterspecifier-parenturl-options"><code>module.register()</code></a> which takes a path or URL to another module that exports the <a href="#asynchronous-hooks-accepted-by-moduleregister">asynchronous hook functions</a>.</p> <p>Similar to <code>registerHooks()</code>, <code>register()</code> can be called in a module preloaded by <code>--import</code> or <code>--require</code>, or called directly within the entry point.</p> <pre class="with-78-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// Use module.register() to register asynchronous hooks in a dedicated thread.</span> <span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>; <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>); <span class="hljs-comment">// If my-app.mjs is loaded statically here as `import './my-app.mjs'`, since ESM</span> <span class="hljs-comment">// dependencies are evaluated before the module that imports them,</span> <span class="hljs-comment">// it's loaded _before_ the hooks are registered above and won't be affected.</span> <span class="hljs-comment">// To ensure the hooks are applied, dynamic import() must be used to load ESM</span> <span class="hljs-comment">// after the hooks are registered.</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.mjs'</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>); <span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>); <span class="hljs-comment">// Use module.register() to register asynchronous hooks in a dedicated thread.</span> <span class="hljs-title function_">register</span>(<span class="hljs-string">'./hooks.mjs'</span>, <span class="hljs-title function_">pathToFileURL</span>(__filename)); <span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.mjs'</span>);</code><button class="copy-button">copy</button></pre> <p>In <code>hooks.mjs</code>:</p> <pre><code class="language-js mjs"><span class="hljs-comment">// hooks.mjs</span> <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>) { <span class="hljs-comment">/* implementation */</span> } <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>) { <span class="hljs-comment">/* implementation */</span> }</code> <button class="copy-button">copy</button></pre> <p>Unlike synchronous hooks, the asynchronous hooks would not run for these modules loaded in the file that calls <code>register()</code>:</p> <!-- eslint-disable no-restricted-globals --> <pre><code class="language-js mjs"><span class="hljs-comment">// register-hooks.js</span> <span class="hljs-keyword">import</span> { register, createRequire } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>; <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>); <span class="hljs-comment">// Asynchronous hooks does not affect modules loaded via custom require()</span> <span class="hljs-comment">// functions created by module.createRequire().</span> <span class="hljs-keyword">const</span> userRequire = <span class="hljs-title function_">createRequire</span>(__filename); <span class="hljs-title function_">userRequire</span>(<span class="hljs-string">'./my-app-2.cjs'</span>); <span class="hljs-comment">// Hooks won't affect this</span></code> <button class="copy-button">copy</button></pre> <!-- eslint-enable no-restricted-globals --> <pre><code class="language-js cjs"><span class="hljs-comment">// register-hooks.js</span> <span class="hljs-keyword">const</span> { register, createRequire } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>); <span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>); <span class="hljs-title function_">register</span>(<span class="hljs-string">'./hooks.mjs'</span>, <span class="hljs-title function_">pathToFileURL</span>(__filename)); <span class="hljs-comment">// Asynchronous hooks does not affect modules loaded via built-in require()</span> <span class="hljs-comment">// in the module calling `register()`</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'./my-app-2.cjs'</span>); <span class="hljs-comment">// Hooks won't affect this</span> <span class="hljs-comment">// .. or custom require() functions created by module.createRequire().</span> <span class="hljs-keyword">const</span> userRequire = <span class="hljs-title function_">createRequire</span>(__filename); <span class="hljs-title function_">userRequire</span>(<span class="hljs-string">'./my-app-3.cjs'</span>); <span class="hljs-comment">// Hooks won't affect this</span></code> <button class="copy-button">copy</button></pre> <p>Asynchronous hooks can also be registered using a <code>data:</code> URL with the <code>--import</code> flag:</p> <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("my-instrumentation", pathToFileURL("./"));'</span> ./my-app.js</code> <button class="copy-button">copy</button></pre> </div><div> <h5>Chaining of asynchronous customization hooks<span><a class="mark" href="#chaining-of-asynchronous-customization-hooks" id="chaining-of-asynchronous-customization-hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_chaining_of_asynchronous_customization_hooks"></a></h5> <p>Chaining of <code>register()</code> work similarly to <code>registerHooks()</code>. If synchronous and asynchronous hooks are mixed, the synchronous hooks are always run first before the asynchronous hooks start running, that is, in the last synchronous hook being run, its next hook includes invocation of the asynchronous hooks.</p> <pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// entrypoint.mjs</span> <span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>; <span class="hljs-title function_">register</span>(<span class="hljs-string">'./foo.mjs'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>); <span class="hljs-title function_">register</span>(<span class="hljs-string">'./bar.mjs'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>); <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> <span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>); <span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>); <span class="hljs-keyword">const</span> parentURL = <span class="hljs-title function_">pathToFileURL</span>(__filename); <span class="hljs-title function_">register</span>(<span class="hljs-string">'./foo.mjs'</span>, parentURL); <span class="hljs-title function_">register</span>(<span class="hljs-string">'./bar.mjs'</span>, parentURL); <span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.mjs'</span>);</code><button class="copy-button">copy</button></pre> <p>If <code>foo.mjs</code> and <code>bar.mjs</code> define a <code>resolve</code> hook, they will be called like so (note the right-to-left, starting with <code>./bar.mjs</code>, then <code>./foo.mjs</code>, then the Node.js default):</p> <p>Node.js default ← <code>./foo.mjs</code> ← <code>./bar.mjs</code></p> <p>When using the asynchronous hooks, the registered hooks also affect subsequent <code>register</code> calls, which takes care of loading hook modules. In the example above, <code>bar.mjs</code> will be resolved and loaded via the hooks registered by <code>foo.mjs</code> (because <code>foo</code>'s hooks will have already been added to the chain). This allows for things like writing hooks in non-JavaScript languages, so long as earlier registered hooks transpile into JavaScript.</p> <p>The <code>register()</code> method cannot be called from the thread running the hook module that exports the asynchronous hooks or its dependencies.</p> </div><div> <h5>Communication with asynchronous module customization hooks<span><a class="mark" href="#communication-with-asynchronous-module-customization-hooks" id="communication-with-asynchronous-module-customization-hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_communication_with_asynchronous_module_customization_hooks"></a></h5> <p>Asynchronous hooks run on a dedicated thread, separate from the main thread that runs application code. This means mutating global variables won't affect the other thread(s), and message channels must be used to communicate between the threads.</p> <p>The <code>register</code> method can be used to pass data to an <a href="#initialize"><code>initialize</code></a> hook. The data passed to the hook may include transferable objects like ports.</p> <pre class="with-53-chars"><input class="js-flavor-toggle" 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>; <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>; <span class="hljs-comment">// This example demonstrates how a message channel can be used to</span> <span class="hljs-comment">// communicate with the hooks, by sending `port2` to the hooks.</span> <span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>(); port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(msg); }); port1.<span class="hljs-title function_">unref</span>(); <span class="hljs-title function_">register</span>(<span class="hljs-string">'./my-hooks.mjs'</span>, { <span class="hljs-attr">parentURL</span>: <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>, <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 }, <span class="hljs-attr">transferList</span>: [port2], });</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>); <span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>); <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>); <span class="hljs-comment">// This example showcases how a message channel can be used to</span> <span class="hljs-comment">// communicate with the hooks, by sending `port2` to the hooks.</span> <span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>(); port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(msg); }); port1.<span class="hljs-title function_">unref</span>(); <span class="hljs-title function_">register</span>(<span class="hljs-string">'./my-hooks.mjs'</span>, { <span class="hljs-attr">parentURL</span>: <span class="hljs-title function_">pathToFileURL</span>(__filename), <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 }, <span class="hljs-attr">transferList</span>: [port2], });</code><button class="copy-button">copy</button></pre> </div><div> <h5>Asynchronous hooks accepted by <code>module.register()</code><span><a class="mark" href="#asynchronous-hooks-accepted-by-moduleregister" id="asynchronous-hooks-accepted-by-moduleregister">#</a></span><a aria-hidden="true" class="legacy" id="module_asynchronous_hooks_accepted_by_module_register"></a></h5> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v20.6.0, v18.19.0</td> <td><p>Added <code>initialize</code> hook to replace <code>globalPreload</code>.</p></td></tr> <tr><td>v18.6.0, v16.17.0</td> <td><p>Add support for chaining loaders.</p></td></tr> <tr><td>v16.12.0</td> <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> <tr><td>v8.8.0</td> <td><p><span>Added in: v8.8.0</span></p></td></tr> </tbody></table> </details> </div> <p>The <a href="#moduleregisterspecifier-parenturl-options"><code>register</code></a> method can be used to register a module that exports a set of hooks. The hooks are functions that are called by Node.js to customize the module resolution and loading process. The exported functions must have specific names and signatures, and they must be exported as named exports.</p> <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>) { <span class="hljs-comment">// Receives data from `register`.</span> } <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>) { <span class="hljs-comment">// Take an `import` or `require` specifier and resolve it to a URL.</span> } <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>) { <span class="hljs-comment">// Take a resolved URL and return the source code to be evaluated.</span> }</code> <button class="copy-button">copy</button></pre> <p>Asynchronous hooks are run in a separate thread, isolated from the main thread where application code runs. That means it is a different <a href="https://tc39.es/ecma262/#realm">realm</a>. The hooks thread may be terminated by the main thread at any time, so do not depend on asynchronous operations (like <code>console.log</code>) to complete. They are inherited into child workers by default.</p> </div><div> <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> <div class="api_metadata"> <span>Added in: v20.6.0, v18.19.0</span> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The data from <code>register(loader, import.meta.url, { data })</code>.</li> </ul> <p>The <code>initialize</code> hook is only accepted by <a href="#moduleregisterspecifier-parenturl-options"><code>register</code></a>. <code>registerHooks()</code> does not support nor need it since initialization done for synchronous hooks can be run directly before the call to <code>registerHooks()</code>.</p> <p>The <code>initialize</code> hook provides a way to define a custom function that runs in the hooks thread when the hooks module is initialized. Initialization happens when the hooks module is registered via <a href="#moduleregisterspecifier-parenturl-options"><code>register</code></a>.</p> <p>This hook can receive data from a <a href="#moduleregisterspecifier-parenturl-options"><code>register</code></a> invocation, including ports and other transferable objects. The return value of <code>initialize</code> can be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a>, in which case it will be awaited before the main application thread execution resumes.</p> <p>Module customization code:</p> <pre><code class="language-js mjs"><span class="hljs-comment">// path-to-my-hooks.js</span> <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>) { 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>); }</code> <button class="copy-button">copy</button></pre> <p>Caller code:</p> <pre class="with-44-chars"><input class="js-flavor-toggle" 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>; <span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>; <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>; <span class="hljs-comment">// This example showcases how a message channel can be used to communicate</span> <span class="hljs-comment">// between the main (application) thread and the hooks running on the hooks</span> <span class="hljs-comment">// thread, by sending `port2` to the `initialize` hook.</span> <span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>(); port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> { assert.<span class="hljs-title function_">strictEqual</span>(msg, <span class="hljs-string">'increment: 2'</span>); }); port1.<span class="hljs-title function_">unref</span>(); <span class="hljs-title function_">register</span>(<span class="hljs-string">'./path-to-my-hooks.js'</span>, { <span class="hljs-attr">parentURL</span>: <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>, <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 }, <span class="hljs-attr">transferList</span>: [port2], });</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>); <span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>); <span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>); <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>); <span class="hljs-comment">// This example showcases how a message channel can be used to communicate</span> <span class="hljs-comment">// between the main (application) thread and the hooks running on the hooks</span> <span class="hljs-comment">// thread, by sending `port2` to the `initialize` hook.</span> <span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>(); port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> { assert.<span class="hljs-title function_">strictEqual</span>(msg, <span class="hljs-string">'increment: 2'</span>); }); port1.<span class="hljs-title function_">unref</span>(); <span class="hljs-title function_">register</span>(<span class="hljs-string">'./path-to-my-hooks.js'</span>, { <span class="hljs-attr">parentURL</span>: <span class="hljs-title function_">pathToFileURL</span>(__filename), <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 }, <span class="hljs-attr">transferList</span>: [port2], });</code><button class="copy-button">copy</button></pre> </div><div> <h5>Asynchronous <code>resolve(specifier, context, nextResolve)</code><span><a class="mark" href="#asynchronous-resolvespecifier-context-nextresolve" id="asynchronous-resolvespecifier-context-nextresolve">#</a></span><a aria-hidden="true" class="legacy" id="module_asynchronous_resolve_specifier_context_nextresolve"></a></h5> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v21.0.0, v20.10.0, v18.19.0</td> <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> <tr><td>v18.6.0, v16.17.0</td> <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> <tr><td>v17.1.0, v16.14.0</td> <td><p>Add support for import assertions.</p></td></tr> </tbody></table> </details> </div> <ul> <li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a></li> <li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <li><code>conditions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string[]></a> Export conditions of the relevant <code>package.json</code></li> <li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object whose key-value pairs represent the attributes for the module to import</li> <li><code>parentURL</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> The module importing this one, or undefined if this is the Node.js entry point</li> </ul> </li> <li><code>nextResolve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The subsequent <code>resolve</code> hook in the chain, or the Node.js default <code>resolve</code> hook after the last user-supplied <code>resolve</code> hook <ul> <li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a></li> <li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> When omitted, the defaults are provided. When provided, defaults are merged in with preference to the provided properties.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> The asynchronous version takes either an object containing the following properties, or a <code>Promise</code> that will resolve to such an object. <ul> <li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type" class="type"><null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> A hint to the <code>load</code> hook (it might be ignored). It can be a module format (such as <code>'commonjs'</code> or <code>'module'</code>) or an arbitrary value like <code>'css'</code> or <code>'yaml'</code>.</li> <li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> The import attributes to use when caching the module (optional; if excluded the input will be used)</li> <li><code>shortCircuit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type" class="type"><boolean></a> A signal that this hook intends to terminate the chain of <code>resolve</code> hooks. <strong>Default:</strong> <code>false</code></li> <li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> The absolute URL to which this input resolves</li> </ul> </li> </ul> <p>The asynchronous version works similarly to the synchronous version, only that the <code>nextResolve</code> function returns a <code>Promise</code>, and the <code>resolve</code> hook itself can return a <code>Promise</code>.</p> <blockquote> <p><strong>Warning</strong> In the case of the asynchronous version, despite support for returning promises and async functions, calls to <code>resolve</code> may still block the main thread which can impact performance.</p> </blockquote> <blockquote> <p><strong>Warning</strong> The <code>resolve</code> hook invoked for <code>require()</code> calls inside CommonJS modules customized by asynchronous hooks does not receive the original specifier passed to <code>require()</code>. Instead, it receives a URL already fully resolved using the default CommonJS resolution.</p> </blockquote> <blockquote> <p><strong>Warning</strong> In the CommonJS modules that are customized by the asynchronous customization hooks, <code>require.resolve()</code> and <code>require()</code> will use <code>"import"</code> export condition instead of <code>"require"</code>, which may cause unexpected behaviors when loading dual packages.</p> </blockquote> <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>) { <span class="hljs-comment">// When calling `defaultResolve`, the arguments can be modified. For example,</span> <span class="hljs-comment">// to change the specifier or add conditions.</span> <span class="hljs-keyword">if</span> (specifier.<span class="hljs-title function_">includes</span>(<span class="hljs-string">'foo'</span>)) { specifier = specifier.<span class="hljs-title function_">replace</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>); <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier, { ...context, <span class="hljs-attr">conditions</span>: [...context.<span class="hljs-property">conditions</span>, <span class="hljs-string">'another-condition'</span>], }); } <span class="hljs-comment">// The hook can also skips default resolution and provide a custom URL.</span> <span class="hljs-keyword">if</span> (specifier === <span class="hljs-string">'special-module'</span>) { <span class="hljs-keyword">return</span> { <span class="hljs-attr">url</span>: <span class="hljs-string">'file:///path/to/special-module.mjs'</span>, <span class="hljs-attr">format</span>: <span class="hljs-string">'module'</span>, <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">// This is mandatory if not calling nextResolve().</span> }; } <span class="hljs-comment">// If no customization is needed, defer to the next hook in the chain which would be the</span> <span class="hljs-comment">// Node.js default resolve if this is the last user-specified loader.</span> <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier); }</code> <button class="copy-button">copy</button></pre> </div><div> <h5>Asynchronous <code>load(url, context, nextLoad)</code><span><a class="mark" href="#asynchronous-loadurl-context-nextload" id="asynchronous-loadurl-context-nextload">#</a></span><a aria-hidden="true" class="legacy" id="module_asynchronous_load_url_context_nextload"></a></h5> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v22.6.0</td> <td><p>Add support for <code>source</code> with format <code>commonjs-typescript</code> and <code>module-typescript</code>.</p></td></tr> <tr><td>v20.6.0</td> <td><p>Add support for <code>source</code> with format <code>commonjs</code>.</p></td></tr> <tr><td>v18.6.0, v16.17.0</td> <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> </tbody></table> </details> </div> <ul> <li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> The URL returned by the <code>resolve</code> chain</li> <li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <li><code>conditions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string[]></a> Export conditions of the relevant <code>package.json</code></li> <li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type" class="type"><null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> The format optionally supplied by the <code>resolve</code> hook chain. This can be any string value as an input; input values do not need to conform to the list of acceptable return values described below.</li> <li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> </li> <li><code>nextLoad</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The subsequent <code>load</code> hook in the chain, or the Node.js default <code>load</code> hook after the last user-supplied <code>load</code> hook <ul> <li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a></li> <li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> When omitted, defaults are provided. When provided, defaults are merged in with preference to the provided properties. In the default <code>nextLoad</code>, if the module pointed to by <code>url</code> does not have explicit module type information, <code>context.format</code> is mandatory. <!-- TODO(joyeecheung): make it at least optionally non-mandatory by allowing JS-style/TS-style module detection when the format is simply unknown --> </li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> The asynchronous version takes either an object containing the following properties, or a <code>Promise</code> that will resolve to such an object. <ul> <li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a></li> <li><code>shortCircuit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type" class="type"><boolean></a> A signal that this hook intends to terminate the chain of <code>load</code> hooks. <strong>Default:</strong> <code>false</code></li> <li><code>source</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> The source for Node.js to evaluate</li> </ul> </li> </ul> <blockquote> <p><strong>Warning</strong>: The asynchronous <code>load</code> hook and namespaced exports from CommonJS modules are incompatible. Attempting to use them together will result in an empty object from the import. This may be addressed in the future. This does not apply to the synchronous <code>load</code> hook, in which case exports can be used as usual.</p> </blockquote> <p>The asynchronous version works similarly to the synchronous version, though when using the asynchronous <code>load</code> hook, omitting vs providing a <code>source</code> for <code>'commonjs'</code> has very different effects:</p> <ul> <li>When a <code>source</code> is provided, all <code>require</code> calls from this module will be processed by the ESM loader with registered <code>resolve</code> and <code>load</code> hooks; all <code>require.resolve</code> calls from this module will be processed by the ESM loader with registered <code>resolve</code> hooks; only a subset of the CommonJS API will be available (e.g. no <code>require.extensions</code>, no <code>require.cache</code>, no <code>require.resolve.paths</code>) and monkey-patching on the CommonJS module loader will not apply.</li> <li>If <code>source</code> is undefined or <code>null</code>, it will be handled by the CommonJS module loader and <code>require</code>/<code>require.resolve</code> calls will not go through the registered hooks. This behavior for nullish <code>source</code> is temporary — in the future, nullish <code>source</code> will not be supported.</li> </ul> <p>These caveats do not apply to the synchronous <code>load</code> hook, in which case the complete set of CommonJS APIs available to the customized CommonJS modules, and <code>require</code>/<code>require.resolve</code> always go through the registered hooks.</p> <p>The Node.js internal asynchronous <code>load</code> implementation, which is the value of <code>next</code> for the last hook in the <code>load</code> chain, returns <code>null</code> for <code>source</code> when <code>format</code> is <code>'commonjs'</code> for backward compatibility. Here is an example hook that would opt-in to using the non-default behavior:</p> <pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>; <span class="hljs-comment">// Asynchronous version accepted by module.register(). This fix is not needed</span> <span class="hljs-comment">// for the synchronous version accepted by module.registerHooks().</span> <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>) { <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> <span class="hljs-title function_">nextLoad</span>(url, context); <span class="hljs-keyword">if</span> (result.<span class="hljs-property">format</span> === <span class="hljs-string">'commonjs'</span>) { result.<span class="hljs-property">source</span> ??= <span class="hljs-keyword">await</span> <span class="hljs-title function_">readFile</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(result.<span class="hljs-property">responseURL</span> ?? url)); } <span class="hljs-keyword">return</span> result; }</code> <button class="copy-button">copy</button></pre> <p>This doesn't apply to the synchronous <code>load</code> hook either, in which case the <code>source</code> returned contains source code loaded by the next hook, regardless of module format.</p> </div></div><div> <h4>Examples<span><a class="mark" href="#examples" id="examples">#</a></span><a aria-hidden="true" class="legacy" id="module_examples"></a></h4> <p>The various module customization hooks can be used together to accomplish wide-ranging customizations of the Node.js code loading and evaluation behaviors.</p> <div> <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> <p>The hook below registers hooks to enable rudimentary support for such specifiers. While this may seem like a significant improvement to Node.js core functionality, there are substantial downsides to actually using these hooks: performance is much slower than loading files from disk, there is no caching, and there is no security.</p> <pre><code class="language-js mjs"><span class="hljs-comment">// https-hooks.mjs</span> <span class="hljs-keyword">import</span> { get } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:https'</span>; <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>) { <span class="hljs-comment">// For JavaScript to be loaded over the network, we need to fetch and</span> <span class="hljs-comment">// return it.</span> <span class="hljs-keyword">if</span> (url.<span class="hljs-title function_">startsWith</span>(<span class="hljs-string">'https://'</span>)) { <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> { <span class="hljs-title function_">get</span>(url, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> { <span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>; res.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>); 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); 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>({ <span class="hljs-comment">// This example assumes all network-provided JavaScript is ES module</span> <span class="hljs-comment">// code.</span> <span class="hljs-attr">format</span>: <span class="hljs-string">'module'</span>, <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">source</span>: data, })); }).<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)); }); } <span class="hljs-comment">// Let Node.js handle all other URLs.</span> <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url); }</code> <button class="copy-button">copy</button></pre> <pre><code class="language-js mjs"><span class="hljs-comment">// main.mjs</span> <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>; <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> <p>With the preceding hooks module, running <code>node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./https-hooks.mjs"));' ./main.mjs</code> prints the current version of CoffeeScript per the module at the URL in <code>main.mjs</code>.</p> <!-- TODO(joyeecheung): add an example on how to implement it with a fetchSync based on workers and Atomics.wait() - or all these examples are too much to be put in the API documentation already and should be put into a repository instead? --> </div><div> <h5>Transpilation<span><a class="mark" href="#transpilation" id="transpilation">#</a></span><a aria-hidden="true" class="legacy" id="module_transpilation"></a></h5> <p>Sources that are in formats Node.js doesn't understand can be converted into JavaScript using the <a href="#synchronous-loadurl-context-nextload"><code>load</code> hook</a>.</p> <p>This is less performant than transpiling source files before running Node.js; transpiler hooks should only be used for development and testing purposes.</p> <div> <h6>Asynchronous version<span><a class="mark" href="#asynchronous-version" id="asynchronous-version">#</a></span><a aria-hidden="true" class="legacy" id="module_asynchronous_version"></a></h6> <pre><code class="language-js mjs"><span class="hljs-comment">// coffeescript-hooks.mjs</span> <span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>; <span class="hljs-keyword">import</span> { findPackageJSON } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>; <span class="hljs-keyword">import</span> coffeescript <span class="hljs-keyword">from</span> <span class="hljs-string">'coffeescript'</span>; <span class="hljs-keyword">const</span> extensionsRegex = <span class="hljs-regexp">/\.(coffee|litcoffee|coffee\.md)$/</span>; <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>) { <span class="hljs-keyword">if</span> (extensionsRegex.<span class="hljs-title function_">test</span>(url)) { <span class="hljs-comment">// CoffeeScript files can be either CommonJS or ES modules. Use a custom format</span> <span class="hljs-comment">// to tell Node.js not to detect its module type.</span> <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, <span class="hljs-attr">format</span>: <span class="hljs-string">'coffee'</span> }); <span class="hljs-comment">// This hook converts CoffeeScript source code into JavaScript source code</span> <span class="hljs-comment">// for all imported CoffeeScript files.</span> <span class="hljs-keyword">const</span> transformedSource = coffeescript.<span class="hljs-title function_">compile</span>(rawSource.<span class="hljs-title function_">toString</span>(), url); <span class="hljs-comment">// To determine how Node.js would interpret the transpilation result,</span> <span class="hljs-comment">// search up the file system for the nearest parent package.json file</span> <span class="hljs-comment">// and read its "type" field.</span> <span class="hljs-keyword">return</span> { <span class="hljs-attr">format</span>: <span class="hljs-keyword">await</span> <span class="hljs-title function_">getPackageType</span>(url), <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">source</span>: transformedSource, }; } <span class="hljs-comment">// Let Node.js handle all other URLs.</span> <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url, context); } <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>) { <span class="hljs-comment">// `url` is only a file path during the first iteration when passed the</span> <span class="hljs-comment">// resolved url from the load() hook</span> <span class="hljs-comment">// an actual file path from load() will contain a file extension as it's</span> <span class="hljs-comment">// required by the spec</span> <span class="hljs-comment">// this simple truthy check for whether `url` contains a file extension will</span> <span class="hljs-comment">// work for most projects but does not cover some edge-cases (such as</span> <span class="hljs-comment">// extensionless files or a url ending in a trailing space)</span> <span class="hljs-keyword">const</span> pJson = <span class="hljs-title function_">findPackageJSON</span>(url); <span class="hljs-keyword">return</span> <span class="hljs-title function_">readFile</span>(pJson, <span class="hljs-string">'utf8'</span>) .<span class="hljs-title function_">then</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-property">parse</span>) .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">json</span>) =></span> json?.<span class="hljs-property">type</span>) .<span class="hljs-title function_">catch</span>(<span class="hljs-function">() =></span> <span class="hljs-literal">undefined</span>); }</code> <button class="copy-button">copy</button></pre> </div><div> <h6>Synchronous version<span><a class="mark" href="#synchronous-version" id="synchronous-version">#</a></span><a aria-hidden="true" class="legacy" id="module_synchronous_version"></a></h6> <pre><code class="language-js mjs"><span class="hljs-comment">// coffeescript-sync-hooks.mjs</span> <span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>; <span class="hljs-keyword">import</span> { registerHooks, findPackageJSON } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>; <span class="hljs-keyword">import</span> coffeescript <span class="hljs-keyword">from</span> <span class="hljs-string">'coffeescript'</span>; <span class="hljs-keyword">const</span> extensionsRegex = <span class="hljs-regexp">/\.(coffee|litcoffee|coffee\.md)$/</span>; <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) { <span class="hljs-keyword">if</span> (extensionsRegex.<span class="hljs-title function_">test</span>(url)) { <span class="hljs-keyword">const</span> { <span class="hljs-attr">source</span>: rawSource } = <span class="hljs-title function_">nextLoad</span>(url, { ...context, <span class="hljs-attr">format</span>: <span class="hljs-string">'coffee'</span> }); <span class="hljs-keyword">const</span> transformedSource = coffeescript.<span class="hljs-title function_">compile</span>(rawSource.<span class="hljs-title function_">toString</span>(), url); <span class="hljs-keyword">return</span> { <span class="hljs-attr">format</span>: <span class="hljs-title function_">getPackageType</span>(url), <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">source</span>: transformedSource, }; } <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url, context); } <span class="hljs-keyword">function</span> <span class="hljs-title function_">getPackageType</span>(<span class="hljs-params">url</span>) { <span class="hljs-keyword">const</span> pJson = <span class="hljs-title function_">findPackageJSON</span>(url); <span class="hljs-keyword">if</span> (!pJson) { <span class="hljs-keyword">return</span> <span class="hljs-literal">undefined</span>; } <span class="hljs-keyword">try</span> { <span class="hljs-keyword">const</span> file = <span class="hljs-title function_">readFileSync</span>(pJson, <span class="hljs-string">'utf-8'</span>); <span class="hljs-keyword">return</span> <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(file)?.<span class="hljs-property">type</span>; } <span class="hljs-keyword">catch</span> { <span class="hljs-keyword">return</span> <span class="hljs-literal">undefined</span>; } } <span class="hljs-title function_">registerHooks</span>({ load });</code> <button class="copy-button">copy</button></pre> </div></div><div> <h5>Running hooks<span><a class="mark" href="#running-hooks" id="running-hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_running_hooks"></a></h5> <pre><code class="language-coffee"><span class="hljs-comment"># main.coffee</span> <span class="hljs-keyword">import</span> { scream } <span class="hljs-keyword">from</span> <span class="hljs-string">'./scream.coffee'</span> console.log scream <span class="hljs-string">'hello, world'</span> <span class="hljs-keyword">import</span> { version } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span> console.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> <pre><code class="language-coffee"><span class="hljs-comment"># scream.coffee</span> <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> <p>For the sake of running the example, add a <code>package.json</code> file containing the module type of the CoffeeScript files.</p> <pre><code class="language-json"><span class="hljs-punctuation">{</span> <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"module"</span> <span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre> <p>This is only for running the example. In real world loaders, <code>getPackageType()</code> must be able to return an <code>format</code> known to Node.js even in the absence of an explicit type in a <code>package.json</code>, or otherwise the <code>nextLoad</code> call would throw <code>ERR_UNKNOWN_FILE_EXTENSION</code> (if undefined) or <code>ERR_UNKNOWN_MODULE_FORMAT</code> (if it's not a known format listed in the <a href="#synchronous-loadurl-context-nextload">load hook</a> documentation).</p> <p>With the preceding hooks modules, running <code>node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./coffeescript-hooks.mjs"));' ./main.coffee</code> or <code>node --import ./coffeescript-sync-hooks.mjs ./main.coffee</code> causes <code>main.coffee</code> to be turned into JavaScript after its source code is loaded from disk but before Node.js executes it; and so on for any <code>.coffee</code>, <code>.litcoffee</code> or <code>.coffee.md</code> files referenced via <code>import</code> statements of any loaded file.</p> </div><div> <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> <p>The previous two examples defined <code>load</code> hooks. This is an example of a <code>resolve</code> hook. This hooks module reads an <code>import-map.json</code> file that defines which specifiers to override to other URLs (this is a very simplistic implementation of a small subset of the "import maps" specification).</p> <div> <h6>Asynchronous version<span><a class="mark" href="#asynchronous-version_1" id="asynchronous-version_1">#</a></span><a aria-hidden="true" class="legacy" id="module_asynchronous_version_1"></a></h6> <pre><code class="language-js mjs"><span class="hljs-comment">// import-map-hooks.js</span> <span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>; <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>)); <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>) { <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">hasOwn</span>(imports, specifier)) { <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(imports[specifier], context); } <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier, context); }</code> <button class="copy-button">copy</button></pre> </div><div> <h6>Synchronous version<span><a class="mark" href="#synchronous-version_1" id="synchronous-version_1">#</a></span><a aria-hidden="true" class="legacy" id="module_synchronous_version_1"></a></h6> <pre><code class="language-js mjs"><span class="hljs-comment">// import-map-sync-hooks.js</span> <span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>; <span class="hljs-keyword">import</span> <span class="hljs-variable language_">module</span> <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>; <span class="hljs-keyword">const</span> { imports } = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'import-map.json'</span>, <span class="hljs-string">'utf-8'</span>)); <span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) { <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">hasOwn</span>(imports, specifier)) { <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(imports[specifier], context); } <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier, context); } <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">registerHooks</span>({ resolve });</code> <button class="copy-button">copy</button></pre> </div><div> <h6>Using the hooks<span><a class="mark" href="#using-the-hooks" id="using-the-hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_using_the_hooks"></a></h6> <p>With these files:</p> <pre><code class="language-js mjs"><span class="hljs-comment">// main.js</span> <span class="hljs-keyword">import</span> <span class="hljs-string">'a-module'</span>;</code> <button class="copy-button">copy</button></pre> <pre><code class="language-json"><span class="hljs-comment">// import-map.json</span> <span class="hljs-punctuation">{</span> <span class="hljs-attr">"imports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span> <span class="hljs-attr">"a-module"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./some-module.js"</span> <span class="hljs-punctuation">}</span> <span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre> <pre><code class="language-js mjs"><span class="hljs-comment">// some-module.js</span> <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> <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> or <code>node --import ./import-map-sync-hooks.js main.js</code> should print <code>some module!</code>.</p> </div></div></div> </section><section><h3>Source Map Support<span><a class="mark" href="#source-map-support" id="source-map-support">#</a></span><a aria-hidden="true" class="legacy" id="module_source_map_support"></a></h3> <div class="api_metadata"> <span>Added in: v13.7.0, v12.17.0</span> </div> <p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> <p>Node.js supports TC39 ECMA-426 <a href="https://tc39.es/ecma426/">Source Map</a> format (it was called Source map revision 3 format).</p> <p>The APIs in this section are helpers for interacting with the source map cache. This cache is populated when source map parsing is enabled and <a href="https://tc39.es/ecma426/#sec-linking-generated-code">source map include directives</a> are found in a modules' footer.</p> <p>To enable source map parsing, Node.js must be run with the flag <a href="cli.html#--enable-source-maps"><code>--enable-source-maps</code></a>, or with code coverage enabled by setting <a href="cli.html#node_v8_coveragedir"><code>NODE_V8_COVERAGE=dir</code></a>, or be enabled programmatically via <a href="#modulesetsourcemapssupportenabled-options"><code>module.setSourceMapsSupport()</code></a>.</p> <pre class="with-26-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// module.mjs</span> <span class="hljs-comment">// In an ECMAScript module</span> <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> <span class="hljs-comment">// In a CommonJS module</span> <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> <div> <h4><code>module.getSourceMapsSupport()</code><span><a class="mark" href="#modulegetsourcemapssupport" id="modulegetsourcemapssupport">#</a></span><a aria-hidden="true" class="legacy" id="module_module_getsourcemapssupport"></a></h4> <div class="api_metadata"> <span>Added in: v23.7.0, v22.14.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <ul> <li><code>enabled</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type" class="type"><boolean></a> If the source maps support is enabled</li> <li><code>nodeModules</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type" class="type"><boolean></a> If the support is enabled for files in <code>node_modules</code>.</li> <li><code>generatedCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type" class="type"><boolean></a> If the support is enabled for generated code from <code>eval</code> or <code>new Function</code>.</li> </ul> </li> </ul> <p>This method returns whether the <a href="https://tc39.es/ecma426/">Source Map v3</a> support for stack traces is enabled.</p> <!-- Anchors to make sure old links find a target --> <p><a id="module_module_findsourcemap_path_error"></a></p> </div><div> <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> <div class="api_metadata"> <span>Added in: v13.7.0, v12.17.0</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a></li> <li>Returns: <a href="module.html#class-modulesourcemap" class="type"><module.SourceMap></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> Returns <code>module.SourceMap</code> if a source map is found, <code>undefined</code> otherwise.</li> </ul> <p><code>path</code> is the resolved path for the file for which a corresponding source map should be fetched.</p> </div><div> <h4><code>module.setSourceMapsSupport(enabled[, options])</code><span><a class="mark" href="#modulesetsourcemapssupportenabled-options" id="modulesetsourcemapssupportenabled-options">#</a></span><a aria-hidden="true" class="legacy" id="module_module_setsourcemapssupport_enabled_options"></a></h4> <div class="api_metadata"> <span>Added in: v23.7.0, v22.14.0</span> </div> <ul> <li><code>enabled</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type" class="type"><boolean></a> Enable the source map support.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Optional <ul> <li><code>nodeModules</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type" class="type"><boolean></a> If enabling the support for files in <code>node_modules</code>. <strong>Default:</strong> <code>false</code>.</li> <li><code>generatedCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type" class="type"><boolean></a> If enabling the support for generated code from <code>eval</code> or <code>new Function</code>. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> </ul> <p>This function enables or disables the <a href="https://tc39.es/ecma426/">Source Map v3</a> support for stack traces.</p> <p>It provides same features as launching Node.js process with commandline options <code>--enable-source-maps</code>, with additional options to alter the support for files in <code>node_modules</code> or generated codes.</p> <p>Only source maps in JavaScript files that are loaded after source maps has been enabled will be parsed and loaded. Preferably, use the commandline options <code>--enable-source-maps</code> to avoid losing track of source maps of modules loaded before this API call.</p> </div><div> <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> <div class="api_metadata"> <span>Added in: v13.7.0, v12.17.0</span> </div> <div> <h5><code>new SourceMap(payload[, { lineLengths }])</code><span><a class="mark" href="#new-sourcemappayload--linelengths-" id="new-sourcemappayload--linelengths-">#</a></span><a aria-hidden="true" class="legacy" id="module_new_sourcemap_payload_linelengths"></a></h5> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v20.5.0</td> <td><p>Add support for <code>lineLengths</code>.</p></td></tr> </tbody></table> </details> </div> <ul> <li><code>payload</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>lineLengths</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type" class="type"><number[]></a></li> </ul> <p>Creates a new <code>sourceMap</code> instance.</p> <p><code>payload</code> is an object with keys matching the <a href="https://tc39.es/ecma426/#sec-source-map-format">Source map format</a>:</p> <ul> <li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a></li> <li><code>version</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type" class="type"><number></a></li> <li><code>sources</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string[]></a></li> <li><code>sourcesContent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string[]></a></li> <li><code>names</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string[]></a></li> <li><code>mappings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a></li> <li><code>sourceRoot</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a></li> </ul> <p><code>lineLengths</code> is an optional array of the length of each line in the generated code.</p> </div><div> <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> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Getter for the payload used to construct the <a href="#class-modulesourcemap"><code>SourceMap</code></a> instance.</p> </div><div> <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> <ul> <li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type" class="type"><number></a> The zero-indexed line number offset in the generated source</li> <li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type" class="type"><number></a> The zero-indexed column number offset in the generated source</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Given a line offset and column offset in the generated source file, returns an object representing the SourceMap range in the original file if found, or an empty object if not.</p> <p>The object returned contains the following keys:</p> <ul> <li><code>generatedLine</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type" class="type"><number></a> The line offset of the start of the range in the generated source</li> <li><code>generatedColumn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type" class="type"><number></a> The column offset of start of the range in the generated source</li> <li><code>originalSource</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> The file name of the original source, as reported in the SourceMap</li> <li><code>originalLine</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type" class="type"><number></a> The line offset of the start of the range in the original source</li> <li><code>originalColumn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type" class="type"><number></a> The column offset of start of the range in the original source</li> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a></li> </ul> <p>The returned value represents the raw range as it appears in the SourceMap, based on zero-indexed offsets, <em>not</em> 1-indexed line and column numbers as they appear in Error messages and CallSite objects.</p> <p>To get the corresponding 1-indexed line and column numbers from a lineNumber and columnNumber as they are reported by Error stacks and CallSite objects, use <code>sourceMap.findOrigin(lineNumber, columnNumber)</code></p> </div><div> <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> <div class="api_metadata"> <span>Added in: v20.4.0, v18.18.0</span> </div> <ul> <li><code>lineNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type" class="type"><number></a> The 1-indexed line number of the call site in the generated source</li> <li><code>columnNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type" class="type"><number></a> The 1-indexed column number of the call site in the generated source</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Given a 1-indexed <code>lineNumber</code> and <code>columnNumber</code> from a call site in the generated source, find the corresponding call site location in the original source.</p> <p>If the <code>lineNumber</code> and <code>columnNumber</code> provided are not found in any source map, then an empty object is returned. Otherwise, the returned object contains the following keys:</p> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type" class="type"><undefined></a> The name of the range in the source map, if one was provided</li> <li><code>fileName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type" class="type"><string></a> The file name of the original source, as reported in the SourceMap</li> <li><code>lineNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type" class="type"><number></a> The 1-indexed lineNumber of the corresponding call site in the original source</li> <li><code>columnNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type" class="type"><number></a> The 1-indexed columnNumber of the corresponding call site in the original source</li> </ul></div></div></section> <!-- API END --> </div> </div> </div> </body> </html>
💾 Save Changes
❌ Cancel