1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="utf-8"> 5 <meta name="viewport" content="width=device-width"> 6 <meta name="nodejs.org:node-version" content="v14.20.1"> 7 <title>Modules: CommonJS modules | Node.js v14.20.1 Documentation</title> 8 <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback"> 9 <link rel="stylesheet" href="assets/style.css"> 10 <link rel="stylesheet" href="assets/hljs.css"> 11 <link rel="canonical" href="https://nodejs.org/api/modules.html"> 12</head> 13<body class="alt apidoc" id="api-section-modules"> 14 <div id="content" class="clearfix"> 15 <div id="column2" class="interior"> 16 <div id="intro" class="interior"> 17 <a href="/" title="Go back to the home page"> 18 Node.js 19 </a> 20 </div> 21 <ul> 22<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> 23<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> 24</ul> 25<hr class="line"> 26<ul> 27<li><a href="assert.html" class="nav-assert">Assertion testing</a></li> 28<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> 29<li><a href="buffer.html" class="nav-buffer">Buffer</a></li> 30<li><a href="addons.html" class="nav-addons">C++ addons</a></li> 31<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> 32<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> 33<li><a href="child_process.html" class="nav-child_process">Child processes</a></li> 34<li><a href="cluster.html" class="nav-cluster">Cluster</a></li> 35<li><a href="cli.html" class="nav-cli">Command-line options</a></li> 36<li><a href="console.html" class="nav-console">Console</a></li> 37<li><a href="corepack.html" class="nav-corepack">Corepack</a></li> 38<li><a href="crypto.html" class="nav-crypto">Crypto</a></li> 39<li><a href="debugger.html" class="nav-debugger">Debugger</a></li> 40<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> 41<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> 42<li><a href="dns.html" class="nav-dns">DNS</a></li> 43<li><a href="domain.html" class="nav-domain">Domain</a></li> 44<li><a href="errors.html" class="nav-errors">Errors</a></li> 45<li><a href="events.html" class="nav-events">Events</a></li> 46<li><a href="fs.html" class="nav-fs">File system</a></li> 47<li><a href="globals.html" class="nav-globals">Globals</a></li> 48<li><a href="http.html" class="nav-http">HTTP</a></li> 49<li><a href="http2.html" class="nav-http2">HTTP/2</a></li> 50<li><a href="https.html" class="nav-https">HTTPS</a></li> 51<li><a href="inspector.html" class="nav-inspector">Inspector</a></li> 52<li><a href="intl.html" class="nav-intl">Internationalization</a></li> 53<li><a href="modules.html" class="nav-modules active">Modules: CommonJS modules</a></li> 54<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> 55<li><a href="module.html" class="nav-module">Modules: <code>module</code> API</a></li> 56<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> 57<li><a href="net.html" class="nav-net">Net</a></li> 58<li><a href="os.html" class="nav-os">OS</a></li> 59<li><a href="path.html" class="nav-path">Path</a></li> 60<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> 61<li><a href="policy.html" class="nav-policy">Policies</a></li> 62<li><a href="process.html" class="nav-process">Process</a></li> 63<li><a href="punycode.html" class="nav-punycode">Punycode</a></li> 64<li><a href="querystring.html" class="nav-querystring">Query strings</a></li> 65<li><a href="readline.html" class="nav-readline">Readline</a></li> 66<li><a href="repl.html" class="nav-repl">REPL</a></li> 67<li><a href="report.html" class="nav-report">Report</a></li> 68<li><a href="stream.html" class="nav-stream">Stream</a></li> 69<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> 70<li><a href="timers.html" class="nav-timers">Timers</a></li> 71<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> 72<li><a href="tracing.html" class="nav-tracing">Trace events</a></li> 73<li><a href="tty.html" class="nav-tty">TTY</a></li> 74<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li> 75<li><a href="url.html" class="nav-url">URL</a></li> 76<li><a href="util.html" class="nav-util">Utilities</a></li> 77<li><a href="v8.html" class="nav-v8">V8</a></li> 78<li><a href="vm.html" class="nav-vm">VM</a></li> 79<li><a href="wasi.html" class="nav-wasi">WASI</a></li> 80<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li> 81<li><a href="zlib.html" class="nav-zlib">Zlib</a></li> 82</ul> 83<hr class="line"> 84<ul> 85<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> 86</ul> 87 </div> 88 89 <div id="column1" data-id="modules" class="interior"> 90 <header> 91 <div class="header-container"> 92 <h1>Node.js v14.20.1 documentation</h1> 93 <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden> 94 <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24"> 95 <path fill="none" d="M0 0h24v24H0z" /> 96 <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"/> 97 <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"/> 98 </svg> 99 <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24"> 100 <path d="M0 0h24v24H0z" fill="none" /> 101 <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"/> 102 </svg> 103 </button> 104 </div> 105 <div id="gtoc"> 106 <ul> 107 <li> 108 <a href="index.html">Index</a> 109 </li> 110 <li> 111 <a href="all.html">View on single page</a> 112 </li> 113 <li> 114 <a href="modules.json">View as JSON</a> 115 </li> 116 117 <li class="version-picker"> 118 <a href="#">View another version <span>▼</span></a> 119 <ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v18.x/api/modules.html">18.x</a></li> 120<li><a href="https://nodejs.org/docs/latest-v17.x/api/modules.html">17.x</a></li> 121<li><a href="https://nodejs.org/docs/latest-v16.x/api/modules.html">16.x <b>LTS</b></a></li> 122<li><a href="https://nodejs.org/docs/latest-v15.x/api/modules.html">15.x</a></li> 123<li><a href="https://nodejs.org/docs/latest-v14.x/api/modules.html">14.x <b>LTS</b></a></li> 124<li><a href="https://nodejs.org/docs/latest-v13.x/api/modules.html">13.x</a></li> 125<li><a href="https://nodejs.org/docs/latest-v12.x/api/modules.html">12.x <b>LTS</b></a></li> 126<li><a href="https://nodejs.org/docs/latest-v11.x/api/modules.html">11.x</a></li> 127<li><a href="https://nodejs.org/docs/latest-v10.x/api/modules.html">10.x</a></li> 128<li><a href="https://nodejs.org/docs/latest-v9.x/api/modules.html">9.x</a></li> 129<li><a href="https://nodejs.org/docs/latest-v8.x/api/modules.html">8.x</a></li> 130<li><a href="https://nodejs.org/docs/latest-v7.x/api/modules.html">7.x</a></li> 131<li><a href="https://nodejs.org/docs/latest-v6.x/api/modules.html">6.x</a></li> 132<li><a href="https://nodejs.org/docs/latest-v5.x/api/modules.html">5.x</a></li> 133<li><a href="https://nodejs.org/docs/latest-v4.x/api/modules.html">4.x</a></li> 134<li><a href="https://nodejs.org/docs/latest-v0.12.x/api/modules.html">0.12.x</a></li> 135<li><a href="https://nodejs.org/docs/latest-v0.10.x/api/modules.html">0.10.x</a></li></ol> 136 </li> 137 138 <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/master/doc/api/modules.md">Edit on GitHub</a></li> 139 </ul> 140 </div> 141 <hr> 142 </header> 143 144 <details id="toc" open><summary>Table of contents</summary><ul> 145<li><span class="stability_2"><a href="#modules_modules_commonjs_modules">Modules: CommonJS modules</a></span> 146<ul> 147<li><a href="#modules_accessing_the_main_module">Accessing the main module</a></li> 148<li><a href="#modules_package_manager_tips">Package manager tips</a></li> 149<li><a href="#modules_the_mjs_extension">The <code>.mjs</code> extension</a></li> 150<li><a href="#modules_all_together">All together...</a></li> 151<li><a href="#modules_caching">Caching</a> 152<ul> 153<li><a href="#modules_module_caching_caveats">Module caching caveats</a></li> 154</ul> 155</li> 156<li><a href="#modules_core_modules">Core modules</a></li> 157<li><a href="#modules_cycles">Cycles</a></li> 158<li><a href="#modules_file_modules">File modules</a></li> 159<li><a href="#modules_folders_as_modules">Folders as modules</a></li> 160<li><a href="#modules_loading_from_node_modules_folders">Loading from <code>node_modules</code> folders</a></li> 161<li><a href="#modules_loading_from_the_global_folders">Loading from the global folders</a></li> 162<li><a href="#modules_the_module_wrapper">The module wrapper</a></li> 163<li><a href="#modules_the_module_scope">The module scope</a> 164<ul> 165<li><a href="#modules_dirname"><code>__dirname</code></a></li> 166<li><a href="#modules_filename"><code>__filename</code></a></li> 167<li><a href="#modules_exports"><code>exports</code></a></li> 168<li><a href="#modules_module"><code>module</code></a></li> 169<li><a href="#modules_require_id"><code>require(id)</code></a> 170<ul> 171<li><a href="#modules_require_cache"><code>require.cache</code></a></li> 172<li><span class="stability_0"><a href="#modules_require_extensions"><code>require.extensions</code></a></span></li> 173<li><a href="#modules_require_main"><code>require.main</code></a></li> 174<li><a href="#modules_require_resolve_request_options"><code>require.resolve(request[, options])</code></a> 175<ul> 176<li><a href="#modules_require_resolve_paths_request"><code>require.resolve.paths(request)</code></a></li> 177</ul> 178</li> 179</ul> 180</li> 181</ul> 182</li> 183<li><a href="#modules_the_module_object">The <code>module</code> object</a> 184<ul> 185<li><a href="#modules_module_children"><code>module.children</code></a></li> 186<li><a href="#modules_module_exports"><code>module.exports</code></a> 187<ul> 188<li><a href="#modules_exports_shortcut"><code>exports</code> shortcut</a></li> 189</ul> 190</li> 191<li><a href="#modules_module_filename"><code>module.filename</code></a></li> 192<li><a href="#modules_module_id"><code>module.id</code></a></li> 193<li><a href="#modules_module_ispreloading"><code>module.isPreloading</code></a></li> 194<li><a href="#modules_module_loaded"><code>module.loaded</code></a></li> 195<li><span class="stability_0"><a href="#modules_module_parent"><code>module.parent</code></a></span></li> 196<li><a href="#modules_module_path"><code>module.path</code></a></li> 197<li><a href="#modules_module_paths"><code>module.paths</code></a></li> 198<li><a href="#modules_module_require_id"><code>module.require(id)</code></a></li> 199</ul> 200</li> 201<li><a href="#modules_the_module_object_1">The <code>Module</code> object</a></li> 202<li><a href="#modules_source_map_v3_support">Source map v3 support</a></li> 203</ul> 204</li> 205</ul></details> 206 207 <div id="apicontent"> 208 <h2>Modules: CommonJS modules<span><a class="mark" href="#modules_modules_commonjs_modules" id="modules_modules_commonjs_modules">#</a></span></h2> 209 210<p></p><div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> 211 212<p>In the Node.js module system, each file is treated as a separate module. For 213example, consider a file named <code>foo.js</code>:</p> 214<pre><code class="language-js"><span class="hljs-keyword">const</span> circle = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./circle.js'</span>); 215<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The area of a circle of radius 4 is <span class="hljs-subst">${circle.area(<span class="hljs-number">4</span>)}</span>`</span>);</code></pre> 216<p>On the first line, <code>foo.js</code> loads the module <code>circle.js</code> that is in the same 217directory as <code>foo.js</code>.</p> 218<p>Here are the contents of <code>circle.js</code>:</p> 219<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-variable constant_">PI</span> } = <span class="hljs-title class_">Math</span>; 220 221<span class="hljs-built_in">exports</span>.<span class="hljs-property">area</span> = <span class="hljs-function">(<span class="hljs-params">r</span>) =></span> <span class="hljs-variable constant_">PI</span> * r ** <span class="hljs-number">2</span>; 222 223<span class="hljs-built_in">exports</span>.<span class="hljs-property">circumference</span> = <span class="hljs-function">(<span class="hljs-params">r</span>) =></span> <span class="hljs-number">2</span> * <span class="hljs-variable constant_">PI</span> * r;</code></pre> 224<p>The module <code>circle.js</code> has exported the functions <code>area()</code> and 225<code>circumference()</code>. Functions and objects are added to the root of a module 226by specifying additional properties on the special <code>exports</code> object.</p> 227<p>Variables local to the module will be private, because the module is wrapped 228in a function by Node.js (see <a href="#modules_the_module_wrapper">module wrapper</a>). 229In this example, the variable <code>PI</code> is private to <code>circle.js</code>.</p> 230<p>The <code>module.exports</code> property can be assigned a new value (such as a function 231or object).</p> 232<p>Below, <code>bar.js</code> makes use of the <code>square</code> module, which exports a Square class:</p> 233<pre><code class="language-js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">Square</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./square.js'</span>); 234<span class="hljs-keyword">const</span> mySquare = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Square</span>(<span class="hljs-number">2</span>); 235<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The area of mySquare is <span class="hljs-subst">${mySquare.area()}</span>`</span>);</code></pre> 236<p>The <code>square</code> module is defined in <code>square.js</code>:</p> 237<pre><code class="language-js"><span class="hljs-comment">// Assigning to exports will not modify module, must use module.exports</span> 238<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-keyword">class</span> <span class="hljs-title class_">Square</span> { 239 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">width</span>) { 240 <span class="hljs-variable language_">this</span>.<span class="hljs-property">width</span> = width; 241 } 242 243 <span class="hljs-title function_">area</span>(<span class="hljs-params"></span>) { 244 <span class="hljs-keyword">return</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">width</span> ** <span class="hljs-number">2</span>; 245 } 246};</code></pre> 247<p>The module system is implemented in the <code>require('module')</code> module.</p> 248<section><h3>Accessing the main module<span><a class="mark" href="#modules_accessing_the_main_module" id="modules_accessing_the_main_module">#</a></span></h3> 249 250<p>When a file is run directly from Node.js, <code>require.main</code> is set to its 251<code>module</code>. That means that it is possible to determine whether a file has been 252run directly by testing <code>require.main === module</code>.</p> 253<p>For a file <code>foo.js</code>, this will be <code>true</code> if run via <code>node foo.js</code>, but 254<code>false</code> if run by <code>require('./foo')</code>.</p> 255<p>Because <code>module</code> provides a <code>filename</code> property (normally equivalent to 256<code>__filename</code>), the entry point of the current application can be obtained 257by checking <code>require.main.filename</code>.</p> 258</section><section><h3>Package manager tips<span><a class="mark" href="#modules_package_manager_tips" id="modules_package_manager_tips">#</a></span></h3> 259 260<p>The semantics of the Node.js <code>require()</code> function were designed to be general 261enough to support reasonable directory structures. Package manager programs 262such as <code>dpkg</code>, <code>rpm</code>, and <code>npm</code> will hopefully find it possible to build 263native packages from Node.js modules without modification.</p> 264<p>Below we give a suggested directory structure that could work:</p> 265<p>Let's say that we wanted to have the folder at 266<code>/usr/lib/node/<some-package>/<some-version></code> hold the contents of a 267specific version of a package.</p> 268<p>Packages can depend on one another. In order to install package <code>foo</code>, it 269may be necessary to install a specific version of package <code>bar</code>. The <code>bar</code> 270package may itself have dependencies, and in some cases, these may even collide 271or form cyclic dependencies.</p> 272<p>Because Node.js looks up the <code>realpath</code> of any modules it loads (that is, it 273resolves symlinks) and then <a href="#modules_loading_from_node_modules_folders">looks for their dependencies in <code>node_modules</code> folders</a>, 274this situation can be resolved with the following architecture:</p> 275<ul> 276<li><code>/usr/lib/node/foo/1.2.3/</code>: Contents of the <code>foo</code> package, version 1.2.3.</li> 277<li><code>/usr/lib/node/bar/4.3.2/</code>: Contents of the <code>bar</code> package that <code>foo</code> depends 278on.</li> 279<li><code>/usr/lib/node/foo/1.2.3/node_modules/bar</code>: Symbolic link to 280<code>/usr/lib/node/bar/4.3.2/</code>.</li> 281<li><code>/usr/lib/node/bar/4.3.2/node_modules/*</code>: Symbolic links to the packages that 282<code>bar</code> depends on.</li> 283</ul> 284<p>Thus, even if a cycle is encountered, or if there are dependency 285conflicts, every module will be able to get a version of its dependency 286that it can use.</p> 287<p>When the code in the <code>foo</code> package does <code>require('bar')</code>, it will get the 288version that is symlinked into <code>/usr/lib/node/foo/1.2.3/node_modules/bar</code>. 289Then, when the code in the <code>bar</code> package calls <code>require('quux')</code>, it'll get 290the version that is symlinked into 291<code>/usr/lib/node/bar/4.3.2/node_modules/quux</code>.</p> 292<p>Furthermore, to make the module lookup process even more optimal, rather 293than putting packages directly in <code>/usr/lib/node</code>, we could put them in 294<code>/usr/lib/node_modules/<name>/<version></code>. Then Node.js will not bother 295looking for missing dependencies in <code>/usr/node_modules</code> or <code>/node_modules</code>.</p> 296<p>In order to make modules available to the Node.js REPL, it might be useful to 297also add the <code>/usr/lib/node_modules</code> folder to the <code>$NODE_PATH</code> environment 298variable. Since the module lookups using <code>node_modules</code> folders are all 299relative, and based on the real path of the files making the calls to 300<code>require()</code>, the packages themselves can be anywhere.</p> 301</section><section><h3>The <code>.mjs</code> extension<span><a class="mark" href="#modules_the_mjs_extension" id="modules_the_mjs_extension">#</a></span></h3> 302<p>It is not possible to <code>require()</code> files that have the <code>.mjs</code> extension. 303Attempting to do so will throw <a href="errors.html#errors_err_require_esm">an error</a>. The <code>.mjs</code> extension is 304reserved for <a href="esm.html">ECMAScript Modules</a> which cannot be loaded via <code>require()</code>. 305See <a href="esm.html">ECMAScript Modules</a> for more details.</p> 306</section><section><h3>All together...<span><a class="mark" href="#modules_all_together" id="modules_all_together">#</a></span></h3> 307 308<p>To get the exact filename that will be loaded when <code>require()</code> is called, use 309the <code>require.resolve()</code> function.</p> 310<p>Putting together all of the above, here is the high-level algorithm 311in pseudocode of what <code>require()</code> does:</p> 312<pre>require(X) from module at path Y 3131. If X is a core module, 314 a. return the core module 315 b. STOP 3162. If X begins with '/' 317 a. set Y to be the filesystem root 3183. If X begins with './' or '/' or '../' 319 a. LOAD_AS_FILE(Y + X) 320 b. LOAD_AS_DIRECTORY(Y + X) 321 c. THROW "not found" 3224. If X begins with '#' 323 a. LOAD_PACKAGE_IMPORTS(X, dirname(Y)) 3245. LOAD_PACKAGE_SELF(X, dirname(Y)) 3256. LOAD_NODE_MODULES(X, dirname(Y)) 3267. THROW "not found" 327 328LOAD_AS_FILE(X) 3291. If X is a file, load X as its file extension format. STOP 3302. If X.js is a file, load X.js as JavaScript text. STOP 3313. If X.json is a file, parse X.json to a JavaScript Object. STOP 3324. If X.node is a file, load X.node as binary addon. STOP 333 334LOAD_INDEX(X) 3351. If X/index.js is a file, load X/index.js as JavaScript text. STOP 3362. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP 3373. If X/index.node is a file, load X/index.node as binary addon. STOP 338 339LOAD_AS_DIRECTORY(X) 3401. If X/package.json is a file, 341 a. Parse X/package.json, and look for "main" field. 342 b. If "main" is a falsy value, GOTO 2. 343 c. let M = X + (json main field) 344 d. LOAD_AS_FILE(M) 345 e. LOAD_INDEX(M) 346 f. LOAD_INDEX(X) DEPRECATED 347 g. THROW "not found" 3482. LOAD_INDEX(X) 349 350LOAD_NODE_MODULES(X, START) 3511. let DIRS = NODE_MODULES_PATHS(START) 3522. for each DIR in DIRS: 353 a. LOAD_PACKAGE_EXPORTS(X, DIR) 354 b. LOAD_AS_FILE(DIR/X) 355 c. LOAD_AS_DIRECTORY(DIR/X) 356 357NODE_MODULES_PATHS(START) 3581. let PARTS = path split(START) 3592. let I = count of PARTS - 1 3603. let DIRS = [GLOBAL_FOLDERS] 3614. while I >= 0, 362 a. if PARTS[I] = "node_modules" CONTINUE 363 b. DIR = path join(PARTS[0 .. I] + "node_modules") 364 c. DIRS = DIRS + DIR 365 d. let I = I - 1 3665. return DIRS 367 368LOAD_PACKAGE_IMPORTS(X, DIR) 3691. Find the closest package scope SCOPE to DIR. 3702. If no scope was found, return. 3713. If the SCOPE/package.json "imports" is null or undefined, return. 3724. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE), 373 ["node", "require"]) <a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>. 3745. RESOLVE_ESM_MATCH(MATCH). 375 376LOAD_PACKAGE_EXPORTS(X, DIR) 3771. Try to interpret X as a combination of NAME and SUBPATH where the name 378 may have a @scope/ prefix and the subpath begins with a slash (`/`). 3792. If X does not match this pattern or DIR/NAME/package.json is not a file, 380 return. 3813. Parse DIR/NAME/package.json, and look for "exports" field. 3824. If "exports" is null or undefined, return. 3835. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), "." + SUBPATH, 384 `package.json` "exports", ["node", "require"]) <a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>. 3856. RESOLVE_ESM_MATCH(MATCH) 386 387LOAD_PACKAGE_SELF(X, DIR) 3881. Find the closest package scope SCOPE to DIR. 3892. If no scope was found, return. 3903. If the SCOPE/package.json "exports" is null or undefined, return. 3914. If the SCOPE/package.json "name" is not the first segment of X, return. 3925. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE), 393 "." + X.slice("name".length), `package.json` "exports", ["node", "require"]) 394 <a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>. 3956. RESOLVE_ESM_MATCH(MATCH) 396 397RESOLVE_ESM_MATCH(MATCH) 3981. let { RESOLVED, EXACT } = MATCH 3992. let RESOLVED_PATH = fileURLToPath(RESOLVED) 4003. If EXACT is true, 401 a. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension 402 format. STOP 4034. Otherwise, if EXACT is false, 404 a. LOAD_AS_FILE(RESOLVED_PATH) 405 b. LOAD_AS_DIRECTORY(RESOLVED_PATH) 4065. THROW "not found" 407</pre> 408</section><section><h3>Caching<span><a class="mark" href="#modules_caching" id="modules_caching">#</a></span></h3> 409 410<p>Modules are cached after the first time they are loaded. This means (among other 411things) that every call to <code>require('foo')</code> will get exactly the same object 412returned, if it would resolve to the same file.</p> 413<p>Provided <code>require.cache</code> is not modified, multiple calls to <code>require('foo')</code> 414will not cause the module code to be executed multiple times. This is an 415important feature. With it, "partially done" objects can be returned, thus 416allowing transitive dependencies to be loaded even when they would cause cycles.</p> 417<p>To have a module execute code multiple times, export a function, and call that 418function.</p> 419<h4>Module caching caveats<span><a class="mark" href="#modules_module_caching_caveats" id="modules_module_caching_caveats">#</a></span></h4> 420 421<p>Modules are cached based on their resolved filename. Since modules may resolve 422to a different filename based on the location of the calling module (loading 423from <code>node_modules</code> folders), it is not a <em>guarantee</em> that <code>require('foo')</code> will 424always return the exact same object, if it would resolve to different files.</p> 425<p>Additionally, on case-insensitive file systems or operating systems, different 426resolved filenames can point to the same file, but the cache will still treat 427them as different modules and will reload the file multiple times. For example, 428<code>require('./foo')</code> and <code>require('./FOO')</code> return two different objects, 429irrespective of whether or not <code>./foo</code> and <code>./FOO</code> are the same file.</p> 430</section><section><h3>Core modules<span><a class="mark" href="#modules_core_modules" id="modules_core_modules">#</a></span></h3> 431 432<div class="api_metadata"> 433<details class="changelog"><summary>History</summary> 434<table> 435<tbody><tr><th>Version</th><th>Changes</th></tr> 436<tr><td>v14.18.0</td> 437<td><p>Added <code>node:</code> import support to <code>require(...)</code>.</p></td></tr> 438</tbody></table> 439</details> 440</div> 441<p>Node.js has several modules compiled into the binary. These modules are 442described in greater detail elsewhere in this documentation.</p> 443<p>The core modules are defined within the Node.js source and are located in the 444<code>lib/</code> folder.</p> 445<p>Core modules are always preferentially loaded if their identifier is 446passed to <code>require()</code>. For instance, <code>require('http')</code> will always 447return the built in HTTP module, even if there is a file by that name.</p> 448<p>Core modules can also be identified using the <code>node:</code> prefix, in which case 449it bypasses the <code>require</code> cache. For instance, <code>require('node:http')</code> will 450always return the built in HTTP module, even if there is <code>require.cache</code> entry 451by that name.</p> 452</section><section><h3>Cycles<span><a class="mark" href="#modules_cycles" id="modules_cycles">#</a></span></h3> 453 454<p>When there are circular <code>require()</code> calls, a module might not have finished 455executing when it is returned.</p> 456<p>Consider this situation:</p> 457<p><code>a.js</code>:</p> 458<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a starting'</span>); 459<span class="hljs-built_in">exports</span>.<span class="hljs-property">done</span> = <span class="hljs-literal">false</span>; 460<span class="hljs-keyword">const</span> b = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./b.js'</span>); 461<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'in a, b.done = %j'</span>, b.<span class="hljs-property">done</span>); 462<span class="hljs-built_in">exports</span>.<span class="hljs-property">done</span> = <span class="hljs-literal">true</span>; 463<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a done'</span>);</code></pre> 464<p><code>b.js</code>:</p> 465<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'b starting'</span>); 466<span class="hljs-built_in">exports</span>.<span class="hljs-property">done</span> = <span class="hljs-literal">false</span>; 467<span class="hljs-keyword">const</span> a = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./a.js'</span>); 468<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'in b, a.done = %j'</span>, a.<span class="hljs-property">done</span>); 469<span class="hljs-built_in">exports</span>.<span class="hljs-property">done</span> = <span class="hljs-literal">true</span>; 470<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'b done'</span>);</code></pre> 471<p><code>main.js</code>:</p> 472<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'main starting'</span>); 473<span class="hljs-keyword">const</span> a = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./a.js'</span>); 474<span class="hljs-keyword">const</span> b = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./b.js'</span>); 475<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'in main, a.done = %j, b.done = %j'</span>, a.<span class="hljs-property">done</span>, b.<span class="hljs-property">done</span>);</code></pre> 476<p>When <code>main.js</code> loads <code>a.js</code>, then <code>a.js</code> in turn loads <code>b.js</code>. At that 477point, <code>b.js</code> tries to load <code>a.js</code>. In order to prevent an infinite 478loop, an <strong>unfinished copy</strong> of the <code>a.js</code> exports object is returned to the 479<code>b.js</code> module. <code>b.js</code> then finishes loading, and its <code>exports</code> object is 480provided to the <code>a.js</code> module.</p> 481<p>By the time <code>main.js</code> has loaded both modules, they're both finished. 482The output of this program would thus be:</p> 483<pre><code class="language-console"><span class="hljs-meta">$ </span><span class="language-bash">node main.js</span> 484main starting 485a starting 486b starting 487in b, a.done = false 488b done 489in a, b.done = true 490a done 491in main, a.done = true, b.done = true</code></pre> 492<p>Careful planning is required to allow cyclic module dependencies to work 493correctly within an application.</p> 494</section><section><h3>File modules<span><a class="mark" href="#modules_file_modules" id="modules_file_modules">#</a></span></h3> 495 496<p>If the exact filename is not found, then Node.js will attempt to load the 497required filename with the added extensions: <code>.js</code>, <code>.json</code>, and finally 498<code>.node</code>.</p> 499<p><code>.js</code> files are interpreted as JavaScript text files, and <code>.json</code> files are 500parsed as JSON text files. <code>.node</code> files are interpreted as compiled addon 501modules loaded with <code>process.dlopen()</code>.</p> 502<p>A required module prefixed with <code>'/'</code> is an absolute path to the file. For 503example, <code>require('/home/marco/foo.js')</code> will load the file at 504<code>/home/marco/foo.js</code>.</p> 505<p>A required module prefixed with <code>'./'</code> is relative to the file calling 506<code>require()</code>. That is, <code>circle.js</code> must be in the same directory as <code>foo.js</code> for 507<code>require('./circle')</code> to find it.</p> 508<p>Without a leading <code>'/'</code>, <code>'./'</code>, or <code>'../'</code> to indicate a file, the module must 509either be a core module or is loaded from a <code>node_modules</code> folder.</p> 510<p>If the given path does not exist, <code>require()</code> will throw an <a href="errors.html#errors_class_error"><code>Error</code></a> with its 511<code>code</code> property set to <code>'MODULE_NOT_FOUND'</code>.</p> 512</section><section><h3>Folders as modules<span><a class="mark" href="#modules_folders_as_modules" id="modules_folders_as_modules">#</a></span></h3> 513 514<p>It is convenient to organize programs and libraries into self-contained 515directories, and then provide a single entry point to those directories. 516There are three ways in which a folder may be passed to <code>require()</code> as 517an argument.</p> 518<p>The first is to create a <a href="packages.html#packages_node_js_package_json_field_definitions"><code>package.json</code></a> file in the root of the folder, 519which specifies a <code>main</code> module. An example <a href="packages.html#packages_node_js_package_json_field_definitions"><code>package.json</code></a> file might 520look like this:</p> 521<pre><code class="language-json"><span class="hljs-punctuation">{</span> <span class="hljs-attr">"name"</span> <span class="hljs-punctuation">:</span> <span class="hljs-string">"some-library"</span><span class="hljs-punctuation">,</span> 522 <span class="hljs-attr">"main"</span> <span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/some-library.js"</span> <span class="hljs-punctuation">}</span></code></pre> 523<p>If this was in a folder at <code>./some-library</code>, then 524<code>require('./some-library')</code> would attempt to load 525<code>./some-library/lib/some-library.js</code>.</p> 526<p>This is the extent of the awareness of <code>package.json</code> files within Node.js.</p> 527<p>If there is no <a href="packages.html#packages_node_js_package_json_field_definitions"><code>package.json</code></a> file present in the directory, or if the 528<a href="packages.html#packages_main"><code>"main"</code></a> entry is missing or cannot be resolved, then Node.js 529will attempt to load an <code>index.js</code> or <code>index.node</code> file out of that 530directory. For example, if there was no <a href="packages.html#packages_node_js_package_json_field_definitions"><code>package.json</code></a> file in the previous 531example, then <code>require('./some-library')</code> would attempt to load:</p> 532<ul> 533<li><code>./some-library/index.js</code></li> 534<li><code>./some-library/index.node</code></li> 535</ul> 536<p>If these attempts fail, then Node.js will report the entire module as missing 537with the default error:</p> 538<pre><code class="language-console">Error: Cannot find module 'some-library'</code></pre> 539</section><section><h3>Loading from <code>node_modules</code> folders<span><a class="mark" href="#modules_loading_from_node_modules_folders" id="modules_loading_from_node_modules_folders">#</a></span></h3> 540 541<p>If the module identifier passed to <code>require()</code> is not a 542<a href="#modules_core_modules">core</a> module, and does not begin with <code>'/'</code>, <code>'../'</code>, or 543<code>'./'</code>, then Node.js starts at the parent directory of the current module, and 544adds <code>/node_modules</code>, and attempts to load the module from that location. 545Node.js will not append <code>node_modules</code> to a path already ending in 546<code>node_modules</code>.</p> 547<p>If it is not found there, then it moves to the parent directory, and so 548on, until the root of the file system is reached.</p> 549<p>For example, if the file at <code>'/home/ry/projects/foo.js'</code> called 550<code>require('bar.js')</code>, then Node.js would look in the following locations, in 551this order:</p> 552<ul> 553<li><code>/home/ry/projects/node_modules/bar.js</code></li> 554<li><code>/home/ry/node_modules/bar.js</code></li> 555<li><code>/home/node_modules/bar.js</code></li> 556<li><code>/node_modules/bar.js</code></li> 557</ul> 558<p>This allows programs to localize their dependencies, so that they do not 559clash.</p> 560<p>It is possible to require specific files or sub modules distributed with a 561module by including a path suffix after the module name. For instance 562<code>require('example-module/path/to/file')</code> would resolve <code>path/to/file</code> 563relative to where <code>example-module</code> is located. The suffixed path follows the 564same module resolution semantics.</p> 565</section><section><h3>Loading from the global folders<span><a class="mark" href="#modules_loading_from_the_global_folders" id="modules_loading_from_the_global_folders">#</a></span></h3> 566 567<p>If the <code>NODE_PATH</code> environment variable is set to a colon-delimited list 568of absolute paths, then Node.js will search those paths for modules if they 569are not found elsewhere.</p> 570<p>On Windows, <code>NODE_PATH</code> is delimited by semicolons (<code>;</code>) instead of colons.</p> 571<p><code>NODE_PATH</code> was originally created to support loading modules from 572varying paths before the current <a href="#modules_all_together">module resolution</a> algorithm was defined.</p> 573<p><code>NODE_PATH</code> is still supported, but is less necessary now that the Node.js 574ecosystem has settled on a convention for locating dependent modules. 575Sometimes deployments that rely on <code>NODE_PATH</code> show surprising behavior 576when people are unaware that <code>NODE_PATH</code> must be set. Sometimes a 577module's dependencies change, causing a different version (or even a 578different module) to be loaded as the <code>NODE_PATH</code> is searched.</p> 579<p>Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:</p> 580<ul> 581<li>1: <code>$HOME/.node_modules</code></li> 582<li>2: <code>$HOME/.node_libraries</code></li> 583<li>3: <code>$PREFIX/lib/node</code></li> 584</ul> 585<p>Where <code>$HOME</code> is the user's home directory, and <code>$PREFIX</code> is the Node.js 586configured <code>node_prefix</code>.</p> 587<p>These are mostly for historic reasons.</p> 588<p>It is strongly encouraged to place dependencies in the local <code>node_modules</code> 589folder. These will be loaded faster, and more reliably.</p> 590</section><section><h3>The module wrapper<span><a class="mark" href="#modules_the_module_wrapper" id="modules_the_module_wrapper">#</a></span></h3> 591 592<p>Before a module's code is executed, Node.js will wrap it with a function 593wrapper that looks like the following:</p> 594<pre><code class="language-js">(<span class="hljs-keyword">function</span>(<span class="hljs-params"><span class="hljs-built_in">exports</span>, <span class="hljs-built_in">require</span>, <span class="hljs-variable language_">module</span>, __filename, __dirname</span>) { 595<span class="hljs-comment">// Module code actually lives in here</span> 596});</code></pre> 597<p>By doing this, Node.js achieves a few things:</p> 598<ul> 599<li>It keeps top-level variables (defined with <code>var</code>, <code>const</code> or <code>let</code>) scoped to 600the module rather than the global object.</li> 601<li>It helps to provide some global-looking variables that are actually specific 602to the module, such as: 603<ul> 604<li>The <code>module</code> and <code>exports</code> objects that the implementor can use to export 605values from the module.</li> 606<li>The convenience variables <code>__filename</code> and <code>__dirname</code>, containing the 607module's absolute filename and directory path.</li> 608</ul> 609</li> 610</ul> 611</section><section><h3>The module scope<span><a class="mark" href="#modules_the_module_scope" id="modules_the_module_scope">#</a></span></h3> 612<h4><code>__dirname</code><span><a class="mark" href="#modules_dirname" id="modules_dirname">#</a></span></h4> 613<div class="api_metadata"> 614<span>Added in: v0.1.27</span> 615</div> 616 617<ul> 618<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 619</ul> 620<p>The directory name of the current module. This is the same as the 621<a href="path.html#path_path_dirname_path"><code>path.dirname()</code></a> of the <a href="#modules_filename"><code>__filename</code></a>.</p> 622<p>Example: running <code>node example.js</code> from <code>/Users/mjr</code></p> 623<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(__dirname); 624<span class="hljs-comment">// Prints: /Users/mjr</span> 625<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(path.<span class="hljs-title function_">dirname</span>(__filename)); 626<span class="hljs-comment">// Prints: /Users/mjr</span></code></pre> 627<h4><code>__filename</code><span><a class="mark" href="#modules_filename" id="modules_filename">#</a></span></h4> 628<div class="api_metadata"> 629<span>Added in: v0.0.1</span> 630</div> 631 632<ul> 633<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 634</ul> 635<p>The file name of the current module. This is the current module file's absolute 636path with symlinks resolved.</p> 637<p>For a main program this is not necessarily the same as the file name used in the 638command line.</p> 639<p>See <a href="#modules_dirname"><code>__dirname</code></a> for the directory name of the current module.</p> 640<p>Examples:</p> 641<p>Running <code>node example.js</code> from <code>/Users/mjr</code></p> 642<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(__filename); 643<span class="hljs-comment">// Prints: /Users/mjr/example.js</span> 644<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(__dirname); 645<span class="hljs-comment">// Prints: /Users/mjr</span></code></pre> 646<p>Given two modules: <code>a</code> and <code>b</code>, where <code>b</code> is a dependency of 647<code>a</code> and there is a directory structure of:</p> 648<ul> 649<li><code>/Users/mjr/app/a.js</code></li> 650<li><code>/Users/mjr/app/node_modules/b/b.js</code></li> 651</ul> 652<p>References to <code>__filename</code> within <code>b.js</code> will return 653<code>/Users/mjr/app/node_modules/b/b.js</code> while references to <code>__filename</code> within 654<code>a.js</code> will return <code>/Users/mjr/app/a.js</code>.</p> 655<h4><code>exports</code><span><a class="mark" href="#modules_exports" id="modules_exports">#</a></span></h4> 656<div class="api_metadata"> 657<span>Added in: v0.1.12</span> 658</div> 659 660<ul> 661<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 662</ul> 663<p>A reference to the <code>module.exports</code> that is shorter to type. 664See the section about the <a href="#modules_exports_shortcut">exports shortcut</a> for details on when to use 665<code>exports</code> and when to use <code>module.exports</code>.</p> 666<h4><code>module</code><span><a class="mark" href="#modules_module" id="modules_module">#</a></span></h4> 667<div class="api_metadata"> 668<span>Added in: v0.1.16</span> 669</div> 670 671<ul> 672<li><a href="modules.html#modules_the_module_object" class="type"><module></a></li> 673</ul> 674<p>A reference to the current module, see the section about the 675<a href="#modules_the_module_object"><code>module</code> object</a>. In particular, <code>module.exports</code> is used for defining what 676a module exports and makes available through <code>require()</code>.</p> 677<h4><code>require(id)</code><span><a class="mark" href="#modules_require_id" id="modules_require_id">#</a></span></h4> 678<div class="api_metadata"> 679<span>Added in: v0.1.13</span> 680</div> 681 682<ul> 683<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> module name or path</li> 684<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> exported module content</li> 685</ul> 686<p>Used to import modules, <code>JSON</code>, and local files. Modules can be imported 687from <code>node_modules</code>. Local modules and JSON files can be imported using 688a relative path (e.g. <code>./</code>, <code>./foo</code>, <code>./bar/baz</code>, <code>../foo</code>) that will be 689resolved against the directory named by <a href="#modules_dirname"><code>__dirname</code></a> (if defined) or 690the current working directory. The relative paths of POSIX style are resolved 691in an OS independent fashion, meaning that the examples above will work on 692Windows in the same way they would on Unix systems.</p> 693<pre><code class="language-js"><span class="hljs-comment">// Importing a local module with a path relative to the `__dirname` or current</span> 694<span class="hljs-comment">// working directory. (On Windows, this would resolve to .\path\myLocalModule.)</span> 695<span class="hljs-keyword">const</span> myLocalModule = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./path/myLocalModule'</span>); 696 697<span class="hljs-comment">// Importing a JSON file:</span> 698<span class="hljs-keyword">const</span> jsonData = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./path/filename.json'</span>); 699 700<span class="hljs-comment">// Importing a module from node_modules or Node.js built-in module:</span> 701<span class="hljs-keyword">const</span> crypto = <span class="hljs-built_in">require</span>(<span class="hljs-string">'crypto'</span>);</code></pre> 702<h5><code>require.cache</code><span><a class="mark" href="#modules_require_cache" id="modules_require_cache">#</a></span></h5> 703<div class="api_metadata"> 704<span>Added in: v0.3.0</span> 705</div> 706<ul> 707<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 708</ul> 709<p>Modules are cached in this object when they are required. By deleting a key 710value from this object, the next <code>require</code> will reload the module. 711This does not apply to <a href="addons.html">native addons</a>, for which reloading will result in an 712error.</p> 713<p>Adding or replacing entries is also possible. This cache is checked before 714native modules and if a name matching a native module is added to the cache, 715only <code>node:</code>-prefixed require calls are going to receive the native module. 716Use with care!</p> 717<!-- eslint-disable node-core/no-duplicate-requires --> 718<pre><code class="language-js"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'assert'</span>); 719<span class="hljs-keyword">const</span> realFs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>); 720 721<span class="hljs-keyword">const</span> fakeFs = {}; 722<span class="hljs-built_in">require</span>.<span class="hljs-property">cache</span>.<span class="hljs-property">fs</span> = { <span class="hljs-attr">exports</span>: fakeFs }; 723 724assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>), fakeFs); 725assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>), realFs);</code></pre> 726<h5><code>require.extensions</code><span><a class="mark" href="#modules_require_extensions" id="modules_require_extensions">#</a></span></h5> 727<div class="api_metadata"> 728<span>Added in: v0.3.0</span><span>Deprecated since: v0.10.6</span> 729</div> 730<p></p><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</div><p></p> 731<ul> 732<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 733</ul> 734<p>Instruct <code>require</code> on how to handle certain file extensions.</p> 735<p>Process files with the extension <code>.sjs</code> as <code>.js</code>:</p> 736<pre><code class="language-js"><span class="hljs-built_in">require</span>.<span class="hljs-property">extensions</span>[<span class="hljs-string">'.sjs'</span>] = <span class="hljs-built_in">require</span>.<span class="hljs-property">extensions</span>[<span class="hljs-string">'.js'</span>];</code></pre> 737<p><strong>Deprecated.</strong> In the past, this list has been used to load non-JavaScript 738modules into Node.js by compiling them on-demand. However, in practice, there 739are much better ways to do this, such as loading modules via some other Node.js 740program, or compiling them to JavaScript ahead of time.</p> 741<p>Avoid using <code>require.extensions</code>. Use could cause subtle bugs and resolving the 742extensions gets slower with each registered extension.</p> 743<h5><code>require.main</code><span><a class="mark" href="#modules_require_main" id="modules_require_main">#</a></span></h5> 744<div class="api_metadata"> 745<span>Added in: v0.1.17</span> 746</div> 747<ul> 748<li><a href="modules.html#modules_the_module_object" class="type"><module></a></li> 749</ul> 750<p>The <code>Module</code> object representing the entry script loaded when the Node.js 751process launched. 752See <a href="#modules_accessing_the_main_module">"Accessing the main module"</a>.</p> 753<p>In <code>entry.js</code> script:</p> 754<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-built_in">require</span>.<span class="hljs-property">main</span>);</code></pre> 755<pre><code class="language-bash">node entry.js</code></pre> 756<!-- eslint-skip --> 757<pre><code class="language-js"><span class="hljs-title class_">Module</span> { 758 <span class="hljs-attr">id</span>: <span class="hljs-string">'.'</span>, 759 <span class="hljs-attr">path</span>: <span class="hljs-string">'/absolute/path/to'</span>, 760 <span class="hljs-attr">exports</span>: {}, 761 <span class="hljs-attr">parent</span>: <span class="hljs-literal">null</span>, 762 <span class="hljs-attr">filename</span>: <span class="hljs-string">'/absolute/path/to/entry.js'</span>, 763 <span class="hljs-attr">loaded</span>: <span class="hljs-literal">false</span>, 764 <span class="hljs-attr">children</span>: [], 765 <span class="hljs-attr">paths</span>: 766 [ <span class="hljs-string">'/absolute/path/to/node_modules'</span>, 767 <span class="hljs-string">'/absolute/path/node_modules'</span>, 768 <span class="hljs-string">'/absolute/node_modules'</span>, 769 <span class="hljs-string">'/node_modules'</span> ] }</code></pre> 770<h5><code>require.resolve(request[, options])</code><span><a class="mark" href="#modules_require_resolve_request_options" id="modules_require_resolve_request_options">#</a></span></h5> 771<div class="api_metadata"> 772<details class="changelog"><summary>History</summary> 773<table> 774<tbody><tr><th>Version</th><th>Changes</th></tr> 775<tr><td>v8.9.0</td> 776<td><p>The <code>paths</code> option is now supported.</p></td></tr> 777<tr><td>v0.3.0</td> 778<td><p><span>Added in: v0.3.0</span></p></td></tr> 779</tbody></table> 780</details> 781</div> 782<ul> 783<li><code>request</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The module path to resolve.</li> 784<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 785<ul> 786<li><code>paths</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> Paths to resolve module location from. If present, these 787paths are used instead of the default resolution paths, with the exception 788of <a href="#modules_loading_from_the_global_folders">GLOBAL_FOLDERS</a> like <code>$HOME/.node_modules</code>, which are always 789included. Each of these paths is used as a starting point for 790the module resolution algorithm, meaning that the <code>node_modules</code> hierarchy 791is checked from this location.</li> 792</ul> 793</li> 794<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 795</ul> 796<p>Use the internal <code>require()</code> machinery to look up the location of a module, 797but rather than loading the module, just return the resolved filename.</p> 798<p>If the module can not be found, a <code>MODULE_NOT_FOUND</code> error is thrown.</p> 799<h6><code>require.resolve.paths(request)</code><span><a class="mark" href="#modules_require_resolve_paths_request" id="modules_require_resolve_paths_request">#</a></span></h6> 800<div class="api_metadata"> 801<span>Added in: v8.9.0</span> 802</div> 803<ul> 804<li><code>request</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The module path whose lookup paths are being retrieved.</li> 805<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#Null_type" class="type"><null></a></li> 806</ul> 807<p>Returns an array containing the paths searched during resolution of <code>request</code> or 808<code>null</code> if the <code>request</code> string references a core module, for example <code>http</code> or 809<code>fs</code>.</p> 810</section><section><h3>The <code>module</code> object<span><a class="mark" href="#modules_the_module_object" id="modules_the_module_object">#</a></span></h3> 811<div class="api_metadata"> 812<span>Added in: v0.1.16</span> 813</div> 814 815 816<ul> 817<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 818</ul> 819<p>In each module, the <code>module</code> free variable is a reference to the object 820representing the current module. For convenience, <code>module.exports</code> is 821also accessible via the <code>exports</code> module-global. <code>module</code> is not actually 822a global but rather local to each module.</p> 823<h4><code>module.children</code><span><a class="mark" href="#modules_module_children" id="modules_module_children">#</a></span></h4> 824<div class="api_metadata"> 825<span>Added in: v0.1.16</span> 826</div> 827<ul> 828<li><a href="modules.html#modules_the_module_object" class="type"><module[]></a></li> 829</ul> 830<p>The module objects required for the first time by this one.</p> 831<h4><code>module.exports</code><span><a class="mark" href="#modules_module_exports" id="modules_module_exports">#</a></span></h4> 832<div class="api_metadata"> 833<span>Added in: v0.1.16</span> 834</div> 835<ul> 836<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 837</ul> 838<p>The <code>module.exports</code> object is created by the <code>Module</code> system. Sometimes this is 839not acceptable; many want their module to be an instance of some class. To do 840this, assign the desired export object to <code>module.exports</code>. Assigning 841the desired object to <code>exports</code> will simply rebind the local <code>exports</code> variable, 842which is probably not what is desired.</p> 843<p>For example, suppose we were making a module called <code>a.js</code>:</p> 844<pre><code class="language-js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>); 845 846<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>(); 847 848<span class="hljs-comment">// Do some work, and after some time emit</span> 849<span class="hljs-comment">// the 'ready' event from the module itself.</span> 850<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> { 851 <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'ready'</span>); 852}, <span class="hljs-number">1000</span>);</code></pre> 853<p>Then in another file we could do:</p> 854<pre><code class="language-js"><span class="hljs-keyword">const</span> a = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./a'</span>); 855a.<span class="hljs-title function_">on</span>(<span class="hljs-string">'ready'</span>, <span class="hljs-function">() =></span> { 856 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'module "a" is ready'</span>); 857});</code></pre> 858<p>Assignment to <code>module.exports</code> must be done immediately. It cannot be 859done in any callbacks. This does not work:</p> 860<p><code>x.js</code>:</p> 861<pre><code class="language-js"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> { 862 <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = { <span class="hljs-attr">a</span>: <span class="hljs-string">'hello'</span> }; 863}, <span class="hljs-number">0</span>);</code></pre> 864<p><code>y.js</code>:</p> 865<pre><code class="language-js"><span class="hljs-keyword">const</span> x = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./x'</span>); 866<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x.<span class="hljs-property">a</span>);</code></pre> 867<h5><code>exports</code> shortcut<span><a class="mark" href="#modules_exports_shortcut" id="modules_exports_shortcut">#</a></span></h5> 868<div class="api_metadata"> 869<span>Added in: v0.1.16</span> 870</div> 871<p>The <code>exports</code> variable is available within a module's file-level scope, and is 872assigned the value of <code>module.exports</code> before the module is evaluated.</p> 873<p>It allows a shortcut, so that <code>module.exports.f = ...</code> can be written more 874succinctly as <code>exports.f = ...</code>. However, be aware that like any variable, if a 875new value is assigned to <code>exports</code>, it is no longer bound to <code>module.exports</code>:</p> 876<pre><code class="language-js"><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>.<span class="hljs-property">hello</span> = <span class="hljs-literal">true</span>; <span class="hljs-comment">// Exported from require of module</span> 877<span class="hljs-built_in">exports</span> = { <span class="hljs-attr">hello</span>: <span class="hljs-literal">false</span> }; <span class="hljs-comment">// Not exported, only available in the module</span></code></pre> 878<p>When the <code>module.exports</code> property is being completely replaced by a new 879object, it is common to also reassign <code>exports</code>:</p> 880<!-- eslint-disable func-name-matching --> 881<pre><code class="language-js"><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-built_in">exports</span> = <span class="hljs-keyword">function</span> <span class="hljs-title function_">Constructor</span>(<span class="hljs-params"></span>) { 882 <span class="hljs-comment">// ... etc.</span> 883};</code></pre> 884<p>To illustrate the behavior, imagine this hypothetical implementation of 885<code>require()</code>, which is quite similar to what is actually done by <code>require()</code>:</p> 886<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">require</span>(<span class="hljs-params"><span class="hljs-comment">/* ... */</span></span>) { 887 <span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = { <span class="hljs-attr">exports</span>: {} }; 888 (<span class="hljs-function">(<span class="hljs-params"><span class="hljs-variable language_">module</span>, <span class="hljs-built_in">exports</span></span>) =></span> { 889 <span class="hljs-comment">// Module code here. In this example, define a function.</span> 890 <span class="hljs-keyword">function</span> <span class="hljs-title function_">someFunc</span>(<span class="hljs-params"></span>) {} 891 <span class="hljs-built_in">exports</span> = someFunc; 892 <span class="hljs-comment">// At this point, exports is no longer a shortcut to module.exports, and</span> 893 <span class="hljs-comment">// this module will still export an empty default object.</span> 894 <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = someFunc; 895 <span class="hljs-comment">// At this point, the module will now export someFunc, instead of the</span> 896 <span class="hljs-comment">// default object.</span> 897 })(<span class="hljs-variable language_">module</span>, <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>); 898 <span class="hljs-keyword">return</span> <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>; 899}</code></pre> 900<h4><code>module.filename</code><span><a class="mark" href="#modules_module_filename" id="modules_module_filename">#</a></span></h4> 901<div class="api_metadata"> 902<span>Added in: v0.1.16</span> 903</div> 904<ul> 905<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 906</ul> 907<p>The fully resolved filename of the module.</p> 908<h4><code>module.id</code><span><a class="mark" href="#modules_module_id" id="modules_module_id">#</a></span></h4> 909<div class="api_metadata"> 910<span>Added in: v0.1.16</span> 911</div> 912<ul> 913<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 914</ul> 915<p>The identifier for the module. Typically this is the fully resolved 916filename.</p> 917<h4><code>module.isPreloading</code><span><a class="mark" href="#modules_module_ispreloading" id="modules_module_ispreloading">#</a></span></h4> 918<div class="api_metadata"> 919<span>Added in: v14.17.0</span> 920</div> 921<ul> 922<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the module is running during the Node.js preload 923phase.</li> 924</ul> 925<h4><code>module.loaded</code><span><a class="mark" href="#modules_module_loaded" id="modules_module_loaded">#</a></span></h4> 926<div class="api_metadata"> 927<span>Added in: v0.1.16</span> 928</div> 929<ul> 930<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 931</ul> 932<p>Whether or not the module is done loading, or is in the process of 933loading.</p> 934<h4><code>module.parent</code><span><a class="mark" href="#modules_module_parent" id="modules_module_parent">#</a></span></h4> 935<div class="api_metadata"> 936<span>Added in: v0.1.16</span><span>Deprecated since: v14.6.0, v12.19.0</span> 937</div> 938<p></p><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Please use <a href="#modules_require_main"><code>require.main</code></a> and 939<a href="#modules_module_children"><code>module.children</code></a> instead.</div><p></p> 940<ul> 941<li><a href="modules.html#modules_the_module_object" class="type"><module></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></li> 942</ul> 943<p>The module that first required this one, or <code>null</code> if the current module is the 944entry point of the current process, or <code>undefined</code> if the module was loaded by 945something that is not a CommonJS module (E.G.: REPL or <code>import</code>).</p> 946<h4><code>module.path</code><span><a class="mark" href="#modules_module_path" id="modules_module_path">#</a></span></h4> 947<div class="api_metadata"> 948<span>Added in: v11.14.0</span> 949</div> 950<ul> 951<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 952</ul> 953<p>The directory name of the module. This is usually the same as the 954<a href="path.html#path_path_dirname_path"><code>path.dirname()</code></a> of the <a href="#modules_module_id"><code>module.id</code></a>.</p> 955<h4><code>module.paths</code><span><a class="mark" href="#modules_module_paths" id="modules_module_paths">#</a></span></h4> 956<div class="api_metadata"> 957<span>Added in: v0.4.0</span> 958</div> 959<ul> 960<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> 961</ul> 962<p>The search paths for the module.</p> 963<h4><code>module.require(id)</code><span><a class="mark" href="#modules_module_require_id" id="modules_module_require_id">#</a></span></h4> 964<div class="api_metadata"> 965<span>Added in: v0.5.1</span> 966</div> 967<ul> 968<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 969<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> exported module content</li> 970</ul> 971<p>The <code>module.require()</code> method provides a way to load a module as if 972<code>require()</code> was called from the original module.</p> 973<p>In order to do this, it is necessary to get a reference to the <code>module</code> object. 974Since <code>require()</code> returns the <code>module.exports</code>, and the <code>module</code> is typically 975<em>only</em> available within a specific module's code, it must be explicitly exported 976in order to be used.</p> 977</section><section><h3>The <code>Module</code> object<span><a class="mark" href="#modules_the_module_object_1" id="modules_the_module_object_1">#</a></span></h3> 978<p>This section was moved to 979<a href="module.html#module_the_module_object">Modules: <code>module</code> core module</a>.</p> 980<!-- Anchors to make sure old links find a target --> 981<ul> 982<li><a id="modules_module_builtinmodules" href="module.html#module_module_builtinmodules"><code>module.builtinModules</code></a></li> 983<li><a id="modules_module_createrequire_filename" href="module.html#module_module_createrequire_filename"><code>module.createRequire(filename)</code></a></li> 984<li><a id="modules_module_createrequirefrompath_filename" href="module.html#module_module_createrequirefrompath_filename"><code>module.createRequireFromPath(filename)</code></a></li> 985<li><a id="modules_module_syncbuiltinesmexports" href="module.html#module_module_syncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a></li> 986</ul> 987</section><section><h3>Source map v3 support<span><a class="mark" href="#modules_source_map_v3_support" id="modules_source_map_v3_support">#</a></span></h3> 988<p>This section was moved to 989<a href="module.html#module_source_map_v3_support">Modules: <code>module</code> core module</a>.</p> 990<!-- Anchors to make sure old links find a target --> 991<ul> 992<li><a id="modules_module_findsourcemap_path_error" href="module.html#module_module_findsourcemap_path"><code>module.findSourceMap(path)</code></a></li> 993<li><a id="modules_class_module_sourcemap" href="module.html#module_class_module_sourcemap">Class: <code>module.SourceMap</code></a> 994<ul> 995<li><a id="modules_new_sourcemap_payload" href="module.html#module_new_sourcemap_payload"><code>new SourceMap(payload)</code></a></li> 996<li><a id="modules_sourcemap_payload" href="module.html#module_sourcemap_payload"><code>sourceMap.payload</code></a></li> 997<li><a id="modules_sourcemap_findentry_linenumber_columnnumber" href="module.html#module_sourcemap_findentry_linenumber_columnnumber"><code>sourceMap.findEntry(lineNumber, columnNumber)</code></a></li> 998</ul> 999</li> 1000</ul></section> 1001 <!-- API END --> 1002 </div> 1003 </div> 1004 </div> 1005 <script> 1006 'use strict'; 1007 { 1008 const kCustomPreference = 'customDarkTheme'; 1009 const userSettings = sessionStorage.getItem(kCustomPreference); 1010 const themeToggleButton = document.getElementById('theme-toggle-btn'); 1011 if (userSettings === null && window.matchMedia) { 1012 const mq = window.matchMedia('(prefers-color-scheme: dark)'); 1013 if ('onchange' in mq) { 1014 function mqChangeListener(e) { 1015 document.body.classList.toggle('dark-mode', e.matches); 1016 } 1017 mq.addEventListener('change', mqChangeListener); 1018 if (themeToggleButton) { 1019 themeToggleButton.addEventListener('click', function() { 1020 mq.removeEventListener('change', mqChangeListener); 1021 }, { once: true }); 1022 } 1023 } 1024 if (mq.matches) { 1025 document.body.classList.add('dark-mode'); 1026 } 1027 } else if (userSettings === 'true') { 1028 document.body.classList.add('dark-mode'); 1029 } 1030 if (themeToggleButton) { 1031 themeToggleButton.hidden = false; 1032 themeToggleButton.addEventListener('click', function() { 1033 sessionStorage.setItem( 1034 kCustomPreference, 1035 document.body.classList.toggle('dark-mode') 1036 ); 1037 }); 1038 } 1039 } 1040 </script> 1041</body> 1042</html> 1043