• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1<!DOCTYPE html>
2<html lang="en">
3<head>
4  <meta charset="utf-8">
5  <meta name="viewport" content="width=device-width">
6  <meta name="nodejs.org:node-version" content="v18.20.1">
7  <title>Modules: CommonJS modules | Node.js v18.20.1 Documentation</title>
8  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback">
9  <link rel="stylesheet" href="assets/style.css">
10  <link rel="stylesheet" href="assets/hljs.css">
11  <link rel="canonical" href="https://nodejs.org/api/modules.html">
12  <script async defer src="assets/api.js" type="text/javascript"></script>
13
14</head>
15<body class="alt apidoc" id="api-section-modules">
16  <div id="content" class="clearfix">
17    <div id="column2" class="interior">
18      <div id="intro" class="interior">
19        <a href="/" title="Go back to the home page">
20          Node.js
21        </a>
22      </div>
23      <ul>
24<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
25<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
26</ul>
27<hr class="line">
28<ul>
29<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
30<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
31<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
32<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
33<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
34<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
35<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
36<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
37<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
38<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
39<li><a href="console.html" class="nav-console">Console</a></li>
40<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
41<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
42<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
43<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
44<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
45<li><a href="dns.html" class="nav-dns">DNS</a></li>
46<li><a href="domain.html" class="nav-domain">Domain</a></li>
47<li><a href="errors.html" class="nav-errors">Errors</a></li>
48<li><a href="events.html" class="nav-events">Events</a></li>
49<li><a href="fs.html" class="nav-fs">File system</a></li>
50<li><a href="globals.html" class="nav-globals">Globals</a></li>
51<li><a href="http.html" class="nav-http">HTTP</a></li>
52<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
53<li><a href="https.html" class="nav-https">HTTPS</a></li>
54<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
55<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
56<li><a href="modules.html" class="nav-modules active">Modules: CommonJS modules</a></li>
57<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
58<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
59<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
60<li><a href="net.html" class="nav-net">Net</a></li>
61<li><a href="os.html" class="nav-os">OS</a></li>
62<li><a href="path.html" class="nav-path">Path</a></li>
63<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
64<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
65<li><a href="process.html" class="nav-process">Process</a></li>
66<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
67<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
68<li><a href="readline.html" class="nav-readline">Readline</a></li>
69<li><a href="repl.html" class="nav-repl">REPL</a></li>
70<li><a href="report.html" class="nav-report">Report</a></li>
71<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
72<li><a href="stream.html" class="nav-stream">Stream</a></li>
73<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
74<li><a href="test.html" class="nav-test">Test runner</a></li>
75<li><a href="timers.html" class="nav-timers">Timers</a></li>
76<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
77<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
78<li><a href="tty.html" class="nav-tty">TTY</a></li>
79<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
80<li><a href="url.html" class="nav-url">URL</a></li>
81<li><a href="util.html" class="nav-util">Utilities</a></li>
82<li><a href="v8.html" class="nav-v8">V8</a></li>
83<li><a href="vm.html" class="nav-vm">VM</a></li>
84<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
85<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
86<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
87<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
88<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
89</ul>
90<hr class="line">
91<ul>
92<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
93</ul>
94    </div>
95
96    <div id="column1" data-id="modules" class="interior">
97      <header class="header">
98        <div class="header-container">
99          <h1>Node.js v18.20.1 documentation</h1>
100          <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden>
101            <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24">
102              <path fill="none" d="M0 0h24v24H0z" />
103              <path d="M11.1 12.08c-2.33-4.51-.5-8.48.53-10.07C6.27 2.2 1.98 6.59 1.98 12c0 .14.02.28.02.42.62-.27 1.29-.42 2-.42 1.66 0 3.18.83 4.1 2.15A4.01 4.01 0 0111 18c0 1.52-.87 2.83-2.12 3.51.98.32 2.03.5 3.11.5 3.5 0 6.58-1.8 8.37-4.52-2.36.23-6.98-.97-9.26-5.41z"/>
104              <path d="M7 16h-.18C6.4 14.84 5.3 14 4 14c-1.66 0-3 1.34-3 3s1.34 3 3 3h3c1.1 0 2-.9 2-2s-.9-2-2-2z"/>
105            </svg>
106            <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24">
107              <path d="M0 0h24v24H0z" fill="none" />
108              <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/>
109            </svg>
110          </button>
111        </div>
112        <div id="gtoc">
113          <ul>
114            <li class="pinned-header">Node.js v18.20.1</li>
115
116    <li class="picker-header">
117      <a href="#">
118        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
119        Table of contents
120      </a>
121
122      <div class="picker"><div class="toc"><ul>
123<li><span class="stability_2"><a href="#modules-commonjs-modules">Modules: CommonJS modules</a></span>
124<ul>
125<li><a href="#enabling">Enabling</a></li>
126<li><a href="#accessing-the-main-module">Accessing the main module</a></li>
127<li><a href="#package-manager-tips">Package manager tips</a></li>
128<li><a href="#the-mjs-extension">The <code>.mjs</code> extension</a></li>
129<li><a href="#all-together">All together</a></li>
130<li><a href="#caching">Caching</a>
131<ul>
132<li><a href="#module-caching-caveats">Module caching caveats</a></li>
133</ul>
134</li>
135<li><a href="#core-modules">Core modules</a></li>
136<li><a href="#cycles">Cycles</a></li>
137<li><a href="#file-modules">File modules</a></li>
138<li><span class="stability_3"><a href="#folders-as-modules">Folders as modules</a></span></li>
139<li><a href="#loading-from-node_modules-folders">Loading from <code>node_modules</code> folders</a></li>
140<li><a href="#loading-from-the-global-folders">Loading from the global folders</a></li>
141<li><a href="#the-module-wrapper">The module wrapper</a></li>
142<li><a href="#the-module-scope">The module scope</a>
143<ul>
144<li><a href="#__dirname"><code>__dirname</code></a></li>
145<li><a href="#__filename"><code>__filename</code></a></li>
146<li><a href="#exports"><code>exports</code></a></li>
147<li><a href="#module"><code>module</code></a></li>
148<li><a href="#requireid"><code>require(id)</code></a>
149<ul>
150<li><a href="#requirecache"><code>require.cache</code></a></li>
151<li><span class="stability_0"><a href="#requireextensions"><code>require.extensions</code></a></span></li>
152<li><a href="#requiremain"><code>require.main</code></a></li>
153<li><a href="#requireresolverequest-options"><code>require.resolve(request[, options])</code></a>
154<ul>
155<li><a href="#requireresolvepathsrequest"><code>require.resolve.paths(request)</code></a></li>
156</ul>
157</li>
158</ul>
159</li>
160</ul>
161</li>
162<li><a href="#the-module-object">The <code>module</code> object</a>
163<ul>
164<li><a href="#modulechildren"><code>module.children</code></a></li>
165<li><a href="#moduleexports"><code>module.exports</code></a>
166<ul>
167<li><a href="#exports-shortcut"><code>exports</code> shortcut</a></li>
168</ul>
169</li>
170<li><a href="#modulefilename"><code>module.filename</code></a></li>
171<li><a href="#moduleid"><code>module.id</code></a></li>
172<li><a href="#moduleispreloading"><code>module.isPreloading</code></a></li>
173<li><a href="#moduleloaded"><code>module.loaded</code></a></li>
174<li><span class="stability_0"><a href="#moduleparent"><code>module.parent</code></a></span></li>
175<li><a href="#modulepath"><code>module.path</code></a></li>
176<li><a href="#modulepaths"><code>module.paths</code></a></li>
177<li><a href="#modulerequireid"><code>module.require(id)</code></a></li>
178</ul>
179</li>
180<li><a href="#the-module-object_1">The <code>Module</code> object</a></li>
181<li><a href="#source-map-v3-support">Source map v3 support</a></li>
182</ul>
183</li>
184</ul></div></div>
185    </li>
186
187
188    <li class="picker-header">
189      <a href="#">
190        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
191        Index
192      </a>
193
194      <div class="picker"><ul>
195<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
196<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
197
198      <li>
199        <a href="index.html">Index</a>
200      </li>
201    </ul>
202
203<hr class="line">
204<ul>
205<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
206<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
207<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
208<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
209<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
210<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
211<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
212<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
213<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
214<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
215<li><a href="console.html" class="nav-console">Console</a></li>
216<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
217<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
218<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
219<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
220<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
221<li><a href="dns.html" class="nav-dns">DNS</a></li>
222<li><a href="domain.html" class="nav-domain">Domain</a></li>
223<li><a href="errors.html" class="nav-errors">Errors</a></li>
224<li><a href="events.html" class="nav-events">Events</a></li>
225<li><a href="fs.html" class="nav-fs">File system</a></li>
226<li><a href="globals.html" class="nav-globals">Globals</a></li>
227<li><a href="http.html" class="nav-http">HTTP</a></li>
228<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
229<li><a href="https.html" class="nav-https">HTTPS</a></li>
230<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
231<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
232<li><a href="modules.html" class="nav-modules active">Modules: CommonJS modules</a></li>
233<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
234<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
235<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
236<li><a href="net.html" class="nav-net">Net</a></li>
237<li><a href="os.html" class="nav-os">OS</a></li>
238<li><a href="path.html" class="nav-path">Path</a></li>
239<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
240<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
241<li><a href="process.html" class="nav-process">Process</a></li>
242<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
243<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
244<li><a href="readline.html" class="nav-readline">Readline</a></li>
245<li><a href="repl.html" class="nav-repl">REPL</a></li>
246<li><a href="report.html" class="nav-report">Report</a></li>
247<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
248<li><a href="stream.html" class="nav-stream">Stream</a></li>
249<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
250<li><a href="test.html" class="nav-test">Test runner</a></li>
251<li><a href="timers.html" class="nav-timers">Timers</a></li>
252<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
253<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
254<li><a href="tty.html" class="nav-tty">TTY</a></li>
255<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
256<li><a href="url.html" class="nav-url">URL</a></li>
257<li><a href="util.html" class="nav-util">Utilities</a></li>
258<li><a href="v8.html" class="nav-v8">V8</a></li>
259<li><a href="vm.html" class="nav-vm">VM</a></li>
260<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
261<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
262<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
263<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
264<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
265</ul>
266<hr class="line">
267<ul>
268<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
269</ul></div>
270    </li>
271
272
273    <li class="picker-header">
274      <a href="#">
275        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
276        Other versions
277      </a>
278      <div class="picker"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v21.x/api/modules.html">21.x</a></li>
279<li><a href="https://nodejs.org/docs/latest-v20.x/api/modules.html">20.x <b>LTS</b></a></li>
280<li><a href="https://nodejs.org/docs/latest-v19.x/api/modules.html">19.x</a></li>
281<li><a href="https://nodejs.org/docs/latest-v18.x/api/modules.html">18.x <b>LTS</b></a></li>
282<li><a href="https://nodejs.org/docs/latest-v17.x/api/modules.html">17.x</a></li>
283<li><a href="https://nodejs.org/docs/latest-v16.x/api/modules.html">16.x</a></li>
284<li><a href="https://nodejs.org/docs/latest-v15.x/api/modules.html">15.x</a></li>
285<li><a href="https://nodejs.org/docs/latest-v14.x/api/modules.html">14.x</a></li>
286<li><a href="https://nodejs.org/docs/latest-v13.x/api/modules.html">13.x</a></li>
287<li><a href="https://nodejs.org/docs/latest-v12.x/api/modules.html">12.x</a></li>
288<li><a href="https://nodejs.org/docs/latest-v11.x/api/modules.html">11.x</a></li>
289<li><a href="https://nodejs.org/docs/latest-v10.x/api/modules.html">10.x</a></li>
290<li><a href="https://nodejs.org/docs/latest-v9.x/api/modules.html">9.x</a></li>
291<li><a href="https://nodejs.org/docs/latest-v8.x/api/modules.html">8.x</a></li>
292<li><a href="https://nodejs.org/docs/latest-v7.x/api/modules.html">7.x</a></li>
293<li><a href="https://nodejs.org/docs/latest-v6.x/api/modules.html">6.x</a></li>
294<li><a href="https://nodejs.org/docs/latest-v5.x/api/modules.html">5.x</a></li>
295<li><a href="https://nodejs.org/docs/latest-v4.x/api/modules.html">4.x</a></li>
296<li><a href="https://nodejs.org/docs/latest-v0.12.x/api/modules.html">0.12.x</a></li>
297<li><a href="https://nodejs.org/docs/latest-v0.10.x/api/modules.html">0.10.x</a></li></ol></div>
298    </li>
299
300            <li class="picker-header">
301              <a href="#">
302                <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
303                Options
304              </a>
305
306              <div class="picker">
307                <ul>
308                  <li>
309                    <a href="all.html">View on single page</a>
310                  </li>
311                  <li>
312                    <a href="modules.json">View as JSON</a>
313                  </li>
314                  <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/main/doc/api/modules.md">Edit on GitHub</a></li>
315                </ul>
316              </div>
317            </li>
318          </ul>
319        </div>
320        <hr>
321      </header>
322
323      <details id="toc" open><summary>Table of contents</summary><ul>
324<li><span class="stability_2"><a href="#modules-commonjs-modules">Modules: CommonJS modules</a></span>
325<ul>
326<li><a href="#enabling">Enabling</a></li>
327<li><a href="#accessing-the-main-module">Accessing the main module</a></li>
328<li><a href="#package-manager-tips">Package manager tips</a></li>
329<li><a href="#the-mjs-extension">The <code>.mjs</code> extension</a></li>
330<li><a href="#all-together">All together</a></li>
331<li><a href="#caching">Caching</a>
332<ul>
333<li><a href="#module-caching-caveats">Module caching caveats</a></li>
334</ul>
335</li>
336<li><a href="#core-modules">Core modules</a></li>
337<li><a href="#cycles">Cycles</a></li>
338<li><a href="#file-modules">File modules</a></li>
339<li><span class="stability_3"><a href="#folders-as-modules">Folders as modules</a></span></li>
340<li><a href="#loading-from-node_modules-folders">Loading from <code>node_modules</code> folders</a></li>
341<li><a href="#loading-from-the-global-folders">Loading from the global folders</a></li>
342<li><a href="#the-module-wrapper">The module wrapper</a></li>
343<li><a href="#the-module-scope">The module scope</a>
344<ul>
345<li><a href="#__dirname"><code>__dirname</code></a></li>
346<li><a href="#__filename"><code>__filename</code></a></li>
347<li><a href="#exports"><code>exports</code></a></li>
348<li><a href="#module"><code>module</code></a></li>
349<li><a href="#requireid"><code>require(id)</code></a>
350<ul>
351<li><a href="#requirecache"><code>require.cache</code></a></li>
352<li><span class="stability_0"><a href="#requireextensions"><code>require.extensions</code></a></span></li>
353<li><a href="#requiremain"><code>require.main</code></a></li>
354<li><a href="#requireresolverequest-options"><code>require.resolve(request[, options])</code></a>
355<ul>
356<li><a href="#requireresolvepathsrequest"><code>require.resolve.paths(request)</code></a></li>
357</ul>
358</li>
359</ul>
360</li>
361</ul>
362</li>
363<li><a href="#the-module-object">The <code>module</code> object</a>
364<ul>
365<li><a href="#modulechildren"><code>module.children</code></a></li>
366<li><a href="#moduleexports"><code>module.exports</code></a>
367<ul>
368<li><a href="#exports-shortcut"><code>exports</code> shortcut</a></li>
369</ul>
370</li>
371<li><a href="#modulefilename"><code>module.filename</code></a></li>
372<li><a href="#moduleid"><code>module.id</code></a></li>
373<li><a href="#moduleispreloading"><code>module.isPreloading</code></a></li>
374<li><a href="#moduleloaded"><code>module.loaded</code></a></li>
375<li><span class="stability_0"><a href="#moduleparent"><code>module.parent</code></a></span></li>
376<li><a href="#modulepath"><code>module.path</code></a></li>
377<li><a href="#modulepaths"><code>module.paths</code></a></li>
378<li><a href="#modulerequireid"><code>module.require(id)</code></a></li>
379</ul>
380</li>
381<li><a href="#the-module-object_1">The <code>Module</code> object</a></li>
382<li><a href="#source-map-v3-support">Source map v3 support</a></li>
383</ul>
384</li>
385</ul></details>
386
387      <div id="apicontent">
388        <h2>Modules: CommonJS modules<span><a class="mark" href="#modules-commonjs-modules" id="modules-commonjs-modules">#</a></span><a aria-hidden="true" class="legacy" id="modules_modules_commonjs_modules"></a></h2>
389
390<p></p><div class="api_stability api_stability_2"><a href="documentation.html#stability-index">Stability: 2</a> - Stable</div><p></p>
391
392<p>CommonJS modules are the original way to package JavaScript code for Node.js.
393Node.js also supports the <a href="esm.html">ECMAScript modules</a> standard used by browsers
394and other JavaScript runtimes.</p>
395<p>In Node.js, each file is treated as a separate module. For
396example, consider a file named <code>foo.js</code>:</p>
397<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>);
398<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> <button class="copy-button">copy</button></pre>
399<p>On the first line, <code>foo.js</code> loads the module <code>circle.js</code> that is in the same
400directory as <code>foo.js</code>.</p>
401<p>Here are the contents of <code>circle.js</code>:</p>
402<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>;
403
404<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>;
405
406<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> <button class="copy-button">copy</button></pre>
407<p>The module <code>circle.js</code> has exported the functions <code>area()</code> and
408<code>circumference()</code>. Functions and objects are added to the root of a module
409by specifying additional properties on the special <code>exports</code> object.</p>
410<p>Variables local to the module will be private, because the module is wrapped
411in a function by Node.js (see <a href="#the-module-wrapper">module wrapper</a>).
412In this example, the variable <code>PI</code> is private to <code>circle.js</code>.</p>
413<p>The <code>module.exports</code> property can be assigned a new value (such as a function
414or object).</p>
415<p>Below, <code>bar.js</code> makes use of the <code>square</code> module, which exports a Square class:</p>
416<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>);
417<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>);
418<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> <button class="copy-button">copy</button></pre>
419<p>The <code>square</code> module is defined in <code>square.js</code>:</p>
420<pre><code class="language-js"><span class="hljs-comment">// Assigning to exports will not modify module, must use module.exports</span>
421<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> {
422  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">width</span>) {
423    <span class="hljs-variable language_">this</span>.<span class="hljs-property">width</span> = width;
424  }
425
426  <span class="hljs-title function_">area</span>(<span class="hljs-params"></span>) {
427    <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>;
428  }
429};</code> <button class="copy-button">copy</button></pre>
430<p>The CommonJS module system is implemented in the <a href="module.html"><code>module</code> core module</a>.</p>
431<section><h3>Enabling<span><a class="mark" href="#enabling" id="enabling">#</a></span><a aria-hidden="true" class="legacy" id="modules_enabling"></a></h3>
432
433<p>Node.js has two module systems: CommonJS modules and <a href="esm.html">ECMAScript modules</a>.</p>
434<p>By default, Node.js will treat the following as CommonJS modules:</p>
435<ul>
436<li>
437<p>Files with a <code>.cjs</code> extension;</p>
438</li>
439<li>
440<p>Files with a <code>.js</code> extension when the nearest parent <code>package.json</code> file
441contains a top-level field <a href="packages.html#type"><code>"type"</code></a> with a value of <code>"commonjs"</code>.</p>
442</li>
443<li>
444<p>Files with a <code>.js</code> extension when the nearest parent <code>package.json</code> file
445doesn't contain a top-level field <a href="packages.html#type"><code>"type"</code></a>. Package authors should include
446the <a href="packages.html#type"><code>"type"</code></a> field, even in packages where all sources are CommonJS. Being
447explicit about the <code>type</code> of the package will make things easier for build
448tools and loaders to determine how the files in the package should be
449interpreted.</p>
450</li>
451<li>
452<p>Files with an extension that is not <code>.mjs</code>, <code>.cjs</code>, <code>.json</code>, <code>.node</code>, or <code>.js</code>
453(when the nearest parent <code>package.json</code> file contains a top-level field
454<a href="packages.html#type"><code>"type"</code></a> with a value of <code>"module"</code>, those files will be recognized as
455CommonJS modules only if they are being included via <code>require()</code>, not when
456used as the command-line entry point of the program).</p>
457</li>
458</ul>
459<p>See <a href="packages.html#determining-module-system">Determining module system</a> for more details.</p>
460<p>Calling <code>require()</code> always use the CommonJS module loader. Calling <code>import()</code>
461always use the ECMAScript module loader.</p>
462</section><section><h3>Accessing the main module<span><a class="mark" href="#accessing-the-main-module" id="accessing-the-main-module">#</a></span><a aria-hidden="true" class="legacy" id="modules_accessing_the_main_module"></a></h3>
463
464<p>When a file is run directly from Node.js, <code>require.main</code> is set to its
465<code>module</code>. That means that it is possible to determine whether a file has been
466run directly by testing <code>require.main === module</code>.</p>
467<p>For a file <code>foo.js</code>, this will be <code>true</code> if run via <code>node foo.js</code>, but
468<code>false</code> if run by <code>require('./foo')</code>.</p>
469<p>When the entry point is not a CommonJS module, <code>require.main</code> is <code>undefined</code>,
470and the main module is out of reach.</p>
471</section><section><h3>Package manager tips<span><a class="mark" href="#package-manager-tips" id="package-manager-tips">#</a></span><a aria-hidden="true" class="legacy" id="modules_package_manager_tips"></a></h3>
472
473<p>The semantics of the Node.js <code>require()</code> function were designed to be general
474enough to support reasonable directory structures. Package manager programs
475such as <code>dpkg</code>, <code>rpm</code>, and <code>npm</code> will hopefully find it possible to build
476native packages from Node.js modules without modification.</p>
477<p>Below we give a suggested directory structure that could work:</p>
478<p>Let's say that we wanted to have the folder at
479<code>/usr/lib/node/&#x3C;some-package>/&#x3C;some-version></code> hold the contents of a
480specific version of a package.</p>
481<p>Packages can depend on one another. In order to install package <code>foo</code>, it
482may be necessary to install a specific version of package <code>bar</code>. The <code>bar</code>
483package may itself have dependencies, and in some cases, these may even collide
484or form cyclic dependencies.</p>
485<p>Because Node.js looks up the <code>realpath</code> of any modules it loads (that is, it
486resolves symlinks) and then <a href="#loading-from-node_modules-folders">looks for their dependencies in <code>node_modules</code> folders</a>,
487this situation can be resolved with the following architecture:</p>
488<ul>
489<li><code>/usr/lib/node/foo/1.2.3/</code>: Contents of the <code>foo</code> package, version 1.2.3.</li>
490<li><code>/usr/lib/node/bar/4.3.2/</code>: Contents of the <code>bar</code> package that <code>foo</code> depends
491on.</li>
492<li><code>/usr/lib/node/foo/1.2.3/node_modules/bar</code>: Symbolic link to
493<code>/usr/lib/node/bar/4.3.2/</code>.</li>
494<li><code>/usr/lib/node/bar/4.3.2/node_modules/*</code>: Symbolic links to the packages that
495<code>bar</code> depends on.</li>
496</ul>
497<p>Thus, even if a cycle is encountered, or if there are dependency
498conflicts, every module will be able to get a version of its dependency
499that it can use.</p>
500<p>When the code in the <code>foo</code> package does <code>require('bar')</code>, it will get the
501version that is symlinked into <code>/usr/lib/node/foo/1.2.3/node_modules/bar</code>.
502Then, when the code in the <code>bar</code> package calls <code>require('quux')</code>, it'll get
503the version that is symlinked into
504<code>/usr/lib/node/bar/4.3.2/node_modules/quux</code>.</p>
505<p>Furthermore, to make the module lookup process even more optimal, rather
506than putting packages directly in <code>/usr/lib/node</code>, we could put them in
507<code>/usr/lib/node_modules/&#x3C;name>/&#x3C;version></code>. Then Node.js will not bother
508looking for missing dependencies in <code>/usr/node_modules</code> or <code>/node_modules</code>.</p>
509<p>In order to make modules available to the Node.js REPL, it might be useful to
510also add the <code>/usr/lib/node_modules</code> folder to the <code>$NODE_PATH</code> environment
511variable. Since the module lookups using <code>node_modules</code> folders are all
512relative, and based on the real path of the files making the calls to
513<code>require()</code>, the packages themselves can be anywhere.</p>
514</section><section><h3>The <code>.mjs</code> extension<span><a class="mark" href="#the-mjs-extension" id="the-mjs-extension">#</a></span><a aria-hidden="true" class="legacy" id="modules_the_mjs_extension"></a></h3>
515<p>Due to the synchronous nature of <code>require()</code>, it is not possible to use it to
516load ECMAScript module files. Attempting to do so will throw a
517<a href="errors.html#err_require_esm"><code>ERR_REQUIRE_ESM</code></a> error. Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import"><code>import()</code></a> instead.</p>
518<p>The <code>.mjs</code> extension is reserved for <a href="esm.html">ECMAScript Modules</a> which cannot be
519loaded via <code>require()</code>. See <a href="packages.html#determining-module-system">Determining module system</a> section for more info
520regarding which files are parsed as ECMAScript modules.</p>
521</section><section><h3>All together<span><a class="mark" href="#all-together" id="all-together">#</a></span><a aria-hidden="true" class="legacy" id="modules_all_together"></a></h3>
522
523<p>To get the exact filename that will be loaded when <code>require()</code> is called, use
524the <code>require.resolve()</code> function.</p>
525<p>Putting together all of the above, here is the high-level algorithm
526in pseudocode of what <code>require()</code> does:</p>
527<pre>require(X) from module at path Y
5281. If X is a core module,
529   a. return the core module
530   b. STOP
5312. If X begins with '/'
532   a. set Y to be the file system root
5333. If X begins with './' or '/' or '../'
534   a. LOAD_AS_FILE(Y + X)
535   b. LOAD_AS_DIRECTORY(Y + X)
536   c. THROW "not found"
5374. If X begins with '#'
538   a. LOAD_PACKAGE_IMPORTS(X, dirname(Y))
5395. LOAD_PACKAGE_SELF(X, dirname(Y))
5406. LOAD_NODE_MODULES(X, dirname(Y))
5417. THROW "not found"
542
543LOAD_AS_FILE(X)
5441. If X is a file, load X as its file extension format. STOP
5452. If X.js is a file, load X.js as JavaScript text. STOP
5463. If X.json is a file, parse X.json to a JavaScript Object. STOP
5474. If X.node is a file, load X.node as binary addon. STOP
548
549LOAD_INDEX(X)
5501. If X/index.js is a file, load X/index.js as JavaScript text. STOP
5512. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
5523. If X/index.node is a file, load X/index.node as binary addon. STOP
553
554LOAD_AS_DIRECTORY(X)
5551. If X/package.json is a file,
556   a. Parse X/package.json, and look for "main" field.
557   b. If "main" is a falsy value, GOTO 2.
558   c. let M = X + (json main field)
559   d. LOAD_AS_FILE(M)
560   e. LOAD_INDEX(M)
561   f. LOAD_INDEX(X) DEPRECATED
562   g. THROW "not found"
5632. LOAD_INDEX(X)
564
565LOAD_NODE_MODULES(X, START)
5661. let DIRS = NODE_MODULES_PATHS(START)
5672. for each DIR in DIRS:
568   a. LOAD_PACKAGE_EXPORTS(X, DIR)
569   b. LOAD_AS_FILE(DIR/X)
570   c. LOAD_AS_DIRECTORY(DIR/X)
571
572NODE_MODULES_PATHS(START)
5731. let PARTS = path split(START)
5742. let I = count of PARTS - 1
5753. let DIRS = []
5764. while I >= 0,
577   a. if PARTS[I] = "node_modules" CONTINUE
578   b. DIR = path join(PARTS[0 .. I] + "node_modules")
579   c. DIRS = DIR + DIRS
580   d. let I = I - 1
5815. return DIRS + GLOBAL_FOLDERS
582
583LOAD_PACKAGE_IMPORTS(X, DIR)
5841. Find the closest package scope SCOPE to DIR.
5852. If no scope was found, return.
5863. If the SCOPE/package.json "imports" is null or undefined, return.
5874. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE),
588  ["node", "require"]) <a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>.
5895. RESOLVE_ESM_MATCH(MATCH).
590
591LOAD_PACKAGE_EXPORTS(X, DIR)
5921. Try to interpret X as a combination of NAME and SUBPATH where the name
593   may have a @scope/ prefix and the subpath begins with a slash (`/`).
5942. If X does not match this pattern or DIR/NAME/package.json is not a file,
595   return.
5963. Parse DIR/NAME/package.json, and look for "exports" field.
5974. If "exports" is null or undefined, return.
5985. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), "." + SUBPATH,
599   `package.json` "exports", ["node", "require"]) <a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>.
6006. RESOLVE_ESM_MATCH(MATCH)
601
602LOAD_PACKAGE_SELF(X, DIR)
6031. Find the closest package scope SCOPE to DIR.
6042. If no scope was found, return.
6053. If the SCOPE/package.json "exports" is null or undefined, return.
6064. If the SCOPE/package.json "name" is not the first segment of X, return.
6075. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE),
608   "." + X.slice("name".length), `package.json` "exports", ["node", "require"])
609   <a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>.
6106. RESOLVE_ESM_MATCH(MATCH)
611
612RESOLVE_ESM_MATCH(MATCH)
6131. let RESOLVED_PATH = fileURLToPath(MATCH)
6142. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension
615   format. STOP
6163. THROW "not found"
617</pre>
618</section><section><h3>Caching<span><a class="mark" href="#caching" id="caching">#</a></span><a aria-hidden="true" class="legacy" id="modules_caching"></a></h3>
619
620<p>Modules are cached after the first time they are loaded. This means (among other
621things) that every call to <code>require('foo')</code> will get exactly the same object
622returned, if it would resolve to the same file.</p>
623<p>Provided <code>require.cache</code> is not modified, multiple calls to <code>require('foo')</code>
624will not cause the module code to be executed multiple times. This is an
625important feature. With it, "partially done" objects can be returned, thus
626allowing transitive dependencies to be loaded even when they would cause cycles.</p>
627<p>To have a module execute code multiple times, export a function, and call that
628function.</p>
629<h4>Module caching caveats<span><a class="mark" href="#module-caching-caveats" id="module-caching-caveats">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_caching_caveats"></a></h4>
630
631<p>Modules are cached based on their resolved filename. Since modules may resolve
632to a different filename based on the location of the calling module (loading
633from <code>node_modules</code> folders), it is not a <em>guarantee</em> that <code>require('foo')</code> will
634always return the exact same object, if it would resolve to different files.</p>
635<p>Additionally, on case-insensitive file systems or operating systems, different
636resolved filenames can point to the same file, but the cache will still treat
637them as different modules and will reload the file multiple times. For example,
638<code>require('./foo')</code> and <code>require('./FOO')</code> return two different objects,
639irrespective of whether or not <code>./foo</code> and <code>./FOO</code> are the same file.</p>
640</section><section><h3>Core modules<span><a class="mark" href="#core-modules" id="core-modules">#</a></span><a aria-hidden="true" class="legacy" id="modules_core_modules"></a></h3>
641
642<div class="api_metadata">
643<details class="changelog"><summary>History</summary>
644<table>
645<tbody><tr><th>Version</th><th>Changes</th></tr>
646<tr><td>v16.0.0, v14.18.0</td>
647<td><p>Added <code>node:</code> import support to <code>require(...)</code>.</p></td></tr>
648</tbody></table>
649</details>
650</div>
651<p>Node.js has several modules compiled into the binary. These modules are
652described in greater detail elsewhere in this documentation.</p>
653<p>The core modules are defined within the Node.js source and are located in the
654<code>lib/</code> folder.</p>
655<p>Core modules can be identified using the <code>node:</code> prefix, in which case
656it bypasses the <code>require</code> cache. For instance, <code>require('node:http')</code> will
657always return the built in HTTP module, even if there is <code>require.cache</code> entry
658by that name.</p>
659<p>Some core modules are always preferentially loaded if their identifier is
660passed to <code>require()</code>. For instance, <code>require('http')</code> will always
661return the built-in HTTP module, even if there is a file by that name. The list
662of core modules that can be loaded without using the <code>node:</code> prefix is exposed
663as <a href="module.html#modulebuiltinmodules"><code>module.builtinModules</code></a>.</p>
664</section><section><h3>Cycles<span><a class="mark" href="#cycles" id="cycles">#</a></span><a aria-hidden="true" class="legacy" id="modules_cycles"></a></h3>
665
666<p>When there are circular <code>require()</code> calls, a module might not have finished
667executing when it is returned.</p>
668<p>Consider this situation:</p>
669<p><code>a.js</code>:</p>
670<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>);
671<span class="hljs-built_in">exports</span>.<span class="hljs-property">done</span> = <span class="hljs-literal">false</span>;
672<span class="hljs-keyword">const</span> b = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./b.js'</span>);
673<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>);
674<span class="hljs-built_in">exports</span>.<span class="hljs-property">done</span> = <span class="hljs-literal">true</span>;
675<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a done'</span>);</code> <button class="copy-button">copy</button></pre>
676<p><code>b.js</code>:</p>
677<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>);
678<span class="hljs-built_in">exports</span>.<span class="hljs-property">done</span> = <span class="hljs-literal">false</span>;
679<span class="hljs-keyword">const</span> a = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./a.js'</span>);
680<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>);
681<span class="hljs-built_in">exports</span>.<span class="hljs-property">done</span> = <span class="hljs-literal">true</span>;
682<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'b done'</span>);</code> <button class="copy-button">copy</button></pre>
683<p><code>main.js</code>:</p>
684<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>);
685<span class="hljs-keyword">const</span> a = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./a.js'</span>);
686<span class="hljs-keyword">const</span> b = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./b.js'</span>);
687<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> <button class="copy-button">copy</button></pre>
688<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
689point, <code>b.js</code> tries to load <code>a.js</code>. In order to prevent an infinite
690loop, an <strong>unfinished copy</strong> of the <code>a.js</code> exports object is returned to the
691<code>b.js</code> module. <code>b.js</code> then finishes loading, and its <code>exports</code> object is
692provided to the <code>a.js</code> module.</p>
693<p>By the time <code>main.js</code> has loaded both modules, they're both finished.
694The output of this program would thus be:</p>
695<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node main.js</span>
696main starting
697a starting
698b starting
699in b, a.done = false
700b done
701in a, b.done = true
702a done
703in main, a.done = true, b.done = true</code> <button class="copy-button">copy</button></pre>
704<p>Careful planning is required to allow cyclic module dependencies to work
705correctly within an application.</p>
706</section><section><h3>File modules<span><a class="mark" href="#file-modules" id="file-modules">#</a></span><a aria-hidden="true" class="legacy" id="modules_file_modules"></a></h3>
707
708<p>If the exact filename is not found, then Node.js will attempt to load the
709required filename with the added extensions: <code>.js</code>, <code>.json</code>, and finally
710<code>.node</code>. When loading a file that has a different extension (e.g. <code>.cjs</code>), its
711full name must be passed to <code>require()</code>, including its file extension (e.g.
712<code>require('./file.cjs')</code>).</p>
713<p><code>.json</code> files are parsed as JSON text files, <code>.node</code> files are interpreted as
714compiled addon modules loaded with <code>process.dlopen()</code>. Files using any other
715extension (or no extension at all) are parsed as JavaScript text files. Refer to
716the <a href="packages.html#determining-module-system">Determining module system</a> section to understand what parse goal will be
717used.</p>
718<p>A required module prefixed with <code>'/'</code> is an absolute path to the file. For
719example, <code>require('/home/marco/foo.js')</code> will load the file at
720<code>/home/marco/foo.js</code>.</p>
721<p>A required module prefixed with <code>'./'</code> is relative to the file calling
722<code>require()</code>. That is, <code>circle.js</code> must be in the same directory as <code>foo.js</code> for
723<code>require('./circle')</code> to find it.</p>
724<p>Without a leading <code>'/'</code>, <code>'./'</code>, or <code>'../'</code> to indicate a file, the module must
725either be a core module or is loaded from a <code>node_modules</code> folder.</p>
726<p>If the given path does not exist, <code>require()</code> will throw a
727<a href="errors.html#module_not_found"><code>MODULE_NOT_FOUND</code></a> error.</p>
728</section><section><h3>Folders as modules<span><a class="mark" href="#folders-as-modules" id="folders-as-modules">#</a></span><a aria-hidden="true" class="legacy" id="modules_folders_as_modules"></a></h3>
729
730<p></p><div class="api_stability api_stability_3"><a href="documentation.html#stability-index">Stability: 3</a> - Legacy: Use <a href="packages.html#subpath-exports">subpath exports</a> or <a href="packages.html#subpath-imports">subpath imports</a> instead.</div><p></p>
731<p>There are three ways in which a folder may be passed to <code>require()</code> as
732an argument.</p>
733<p>The first is to create a <a href="packages.html#nodejs-packagejson-field-definitions"><code>package.json</code></a> file in the root of the folder,
734which specifies a <code>main</code> module. An example <a href="packages.html#nodejs-packagejson-field-definitions"><code>package.json</code></a> file might
735look like this:</p>
736<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>
737  <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> <button class="copy-button">copy</button></pre>
738<p>If this was in a folder at <code>./some-library</code>, then
739<code>require('./some-library')</code> would attempt to load
740<code>./some-library/lib/some-library.js</code>.</p>
741<p>If there is no <a href="packages.html#nodejs-packagejson-field-definitions"><code>package.json</code></a> file present in the directory, or if the
742<a href="packages.html#main"><code>"main"</code></a> entry is missing or cannot be resolved, then Node.js
743will attempt to load an <code>index.js</code> or <code>index.node</code> file out of that
744directory. For example, if there was no <a href="packages.html#nodejs-packagejson-field-definitions"><code>package.json</code></a> file in the previous
745example, then <code>require('./some-library')</code> would attempt to load:</p>
746<ul>
747<li><code>./some-library/index.js</code></li>
748<li><code>./some-library/index.node</code></li>
749</ul>
750<p>If these attempts fail, then Node.js will report the entire module as missing
751with the default error:</p>
752<pre><code class="language-console">Error: Cannot find module 'some-library'</code> <button class="copy-button">copy</button></pre>
753<p>In all three above cases, an <code>import('./some-library')</code> call would result in a
754<a href="errors.html#err_unsupported_dir_import"><code>ERR_UNSUPPORTED_DIR_IMPORT</code></a> error. Using package <a href="packages.html#subpath-exports">subpath exports</a> or
755<a href="packages.html#subpath-imports">subpath imports</a> can provide the same containment organization benefits as
756folders as modules, and work for both <code>require</code> and <code>import</code>.</p>
757</section><section><h3>Loading from <code>node_modules</code> folders<span><a class="mark" href="#loading-from-node_modules-folders" id="loading-from-node_modules-folders">#</a></span><a aria-hidden="true" class="legacy" id="modules_loading_from_node_modules_folders"></a></h3>
758
759<p>If the module identifier passed to <code>require()</code> is not a
760<a href="#core-modules">core</a> module, and does not begin with <code>'/'</code>, <code>'../'</code>, or
761<code>'./'</code>, then Node.js starts at the directory of the current module, and
762adds <code>/node_modules</code>, and attempts to load the module from that location.
763Node.js will not append <code>node_modules</code> to a path already ending in
764<code>node_modules</code>.</p>
765<p>If it is not found there, then it moves to the parent directory, and so
766on, until the root of the file system is reached.</p>
767<p>For example, if the file at <code>'/home/ry/projects/foo.js'</code> called
768<code>require('bar.js')</code>, then Node.js would look in the following locations, in
769this order:</p>
770<ul>
771<li><code>/home/ry/projects/node_modules/bar.js</code></li>
772<li><code>/home/ry/node_modules/bar.js</code></li>
773<li><code>/home/node_modules/bar.js</code></li>
774<li><code>/node_modules/bar.js</code></li>
775</ul>
776<p>This allows programs to localize their dependencies, so that they do not
777clash.</p>
778<p>It is possible to require specific files or sub modules distributed with a
779module by including a path suffix after the module name. For instance
780<code>require('example-module/path/to/file')</code> would resolve <code>path/to/file</code>
781relative to where <code>example-module</code> is located. The suffixed path follows the
782same module resolution semantics.</p>
783</section><section><h3>Loading from the global folders<span><a class="mark" href="#loading-from-the-global-folders" id="loading-from-the-global-folders">#</a></span><a aria-hidden="true" class="legacy" id="modules_loading_from_the_global_folders"></a></h3>
784
785<p>If the <code>NODE_PATH</code> environment variable is set to a colon-delimited list
786of absolute paths, then Node.js will search those paths for modules if they
787are not found elsewhere.</p>
788<p>On Windows, <code>NODE_PATH</code> is delimited by semicolons (<code>;</code>) instead of colons.</p>
789<p><code>NODE_PATH</code> was originally created to support loading modules from
790varying paths before the current <a href="#all-together">module resolution</a> algorithm was defined.</p>
791<p><code>NODE_PATH</code> is still supported, but is less necessary now that the Node.js
792ecosystem has settled on a convention for locating dependent modules.
793Sometimes deployments that rely on <code>NODE_PATH</code> show surprising behavior
794when people are unaware that <code>NODE_PATH</code> must be set. Sometimes a
795module's dependencies change, causing a different version (or even a
796different module) to be loaded as the <code>NODE_PATH</code> is searched.</p>
797<p>Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:</p>
798<ul>
799<li>1: <code>$HOME/.node_modules</code></li>
800<li>2: <code>$HOME/.node_libraries</code></li>
801<li>3: <code>$PREFIX/lib/node</code></li>
802</ul>
803<p>Where <code>$HOME</code> is the user's home directory, and <code>$PREFIX</code> is the Node.js
804configured <code>node_prefix</code>.</p>
805<p>These are mostly for historic reasons.</p>
806<p>It is strongly encouraged to place dependencies in the local <code>node_modules</code>
807folder. These will be loaded faster, and more reliably.</p>
808</section><section><h3>The module wrapper<span><a class="mark" href="#the-module-wrapper" id="the-module-wrapper">#</a></span><a aria-hidden="true" class="legacy" id="modules_the_module_wrapper"></a></h3>
809
810<p>Before a module's code is executed, Node.js will wrap it with a function
811wrapper that looks like the following:</p>
812<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>) {
813<span class="hljs-comment">// Module code actually lives in here</span>
814});</code> <button class="copy-button">copy</button></pre>
815<p>By doing this, Node.js achieves a few things:</p>
816<ul>
817<li>It keeps top-level variables (defined with <code>var</code>, <code>const</code>, or <code>let</code>) scoped to
818the module rather than the global object.</li>
819<li>It helps to provide some global-looking variables that are actually specific
820to the module, such as:
821<ul>
822<li>The <code>module</code> and <code>exports</code> objects that the implementor can use to export
823values from the module.</li>
824<li>The convenience variables <code>__filename</code> and <code>__dirname</code>, containing the
825module's absolute filename and directory path.</li>
826</ul>
827</li>
828</ul>
829</section><section><h3>The module scope<span><a class="mark" href="#the-module-scope" id="the-module-scope">#</a></span><a aria-hidden="true" class="legacy" id="modules_the_module_scope"></a></h3>
830<h4><code>__dirname</code><span><a class="mark" href="#__dirname" id="__dirname">#</a></span><a aria-hidden="true" class="legacy" id="modules_dirname"></a></h4>
831<div class="api_metadata">
832<span>Added in: v0.1.27</span>
833</div>
834
835<ul>
836<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
837</ul>
838<p>The directory name of the current module. This is the same as the
839<a href="path.html#pathdirnamepath"><code>path.dirname()</code></a> of the <a href="#__filename"><code>__filename</code></a>.</p>
840<p>Example: running <code>node example.js</code> from <code>/Users/mjr</code></p>
841<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(__dirname);
842<span class="hljs-comment">// Prints: /Users/mjr</span>
843<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(path.<span class="hljs-title function_">dirname</span>(__filename));
844<span class="hljs-comment">// Prints: /Users/mjr</span></code> <button class="copy-button">copy</button></pre>
845<h4><code>__filename</code><span><a class="mark" href="#__filename" id="__filename">#</a></span><a aria-hidden="true" class="legacy" id="modules_filename"></a></h4>
846<div class="api_metadata">
847<span>Added in: v0.0.1</span>
848</div>
849
850<ul>
851<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
852</ul>
853<p>The file name of the current module. This is the current module file's absolute
854path with symlinks resolved.</p>
855<p>For a main program this is not necessarily the same as the file name used in the
856command line.</p>
857<p>See <a href="#__dirname"><code>__dirname</code></a> for the directory name of the current module.</p>
858<p>Examples:</p>
859<p>Running <code>node example.js</code> from <code>/Users/mjr</code></p>
860<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(__filename);
861<span class="hljs-comment">// Prints: /Users/mjr/example.js</span>
862<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(__dirname);
863<span class="hljs-comment">// Prints: /Users/mjr</span></code> <button class="copy-button">copy</button></pre>
864<p>Given two modules: <code>a</code> and <code>b</code>, where <code>b</code> is a dependency of
865<code>a</code> and there is a directory structure of:</p>
866<ul>
867<li><code>/Users/mjr/app/a.js</code></li>
868<li><code>/Users/mjr/app/node_modules/b/b.js</code></li>
869</ul>
870<p>References to <code>__filename</code> within <code>b.js</code> will return
871<code>/Users/mjr/app/node_modules/b/b.js</code> while references to <code>__filename</code> within
872<code>a.js</code> will return <code>/Users/mjr/app/a.js</code>.</p>
873<h4><code>exports</code><span><a class="mark" href="#exports" id="exports">#</a></span><a aria-hidden="true" class="legacy" id="modules_exports"></a></h4>
874<div class="api_metadata">
875<span>Added in: v0.1.12</span>
876</div>
877
878<ul>
879<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
880</ul>
881<p>A reference to the <code>module.exports</code> that is shorter to type.
882See the section about the <a href="#exports-shortcut">exports shortcut</a> for details on when to use
883<code>exports</code> and when to use <code>module.exports</code>.</p>
884<h4><code>module</code><span><a class="mark" href="#module" id="module">#</a></span><a aria-hidden="true" class="legacy" id="modules_module"></a></h4>
885<div class="api_metadata">
886<span>Added in: v0.1.16</span>
887</div>
888
889<ul>
890<li><a href="modules.html#the-module-object" class="type">&#x3C;module></a></li>
891</ul>
892<p>A reference to the current module, see the section about the
893<a href="#the-module-object"><code>module</code> object</a>. In particular, <code>module.exports</code> is used for defining what
894a module exports and makes available through <code>require()</code>.</p>
895<h4><code>require(id)</code><span><a class="mark" href="#requireid" id="requireid">#</a></span><a aria-hidden="true" class="legacy" id="modules_require_id"></a></h4>
896<div class="api_metadata">
897<span>Added in: v0.1.13</span>
898</div>
899
900<ul>
901<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> module name or path</li>
902<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> exported module content</li>
903</ul>
904<p>Used to import modules, <code>JSON</code>, and local files. Modules can be imported
905from <code>node_modules</code>. Local modules and JSON files can be imported using
906a relative path (e.g. <code>./</code>, <code>./foo</code>, <code>./bar/baz</code>, <code>../foo</code>) that will be
907resolved against the directory named by <a href="#__dirname"><code>__dirname</code></a> (if defined) or
908the current working directory. The relative paths of POSIX style are resolved
909in an OS independent fashion, meaning that the examples above will work on
910Windows in the same way they would on Unix systems.</p>
911<pre><code class="language-js"><span class="hljs-comment">// Importing a local module with a path relative to the `__dirname` or current</span>
912<span class="hljs-comment">// working directory. (On Windows, this would resolve to .\path\myLocalModule.)</span>
913<span class="hljs-keyword">const</span> myLocalModule = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./path/myLocalModule'</span>);
914
915<span class="hljs-comment">// Importing a JSON file:</span>
916<span class="hljs-keyword">const</span> jsonData = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./path/filename.json'</span>);
917
918<span class="hljs-comment">// Importing a module from node_modules or Node.js built-in module:</span>
919<span class="hljs-keyword">const</span> crypto = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);</code> <button class="copy-button">copy</button></pre>
920<h5><code>require.cache</code><span><a class="mark" href="#requirecache" id="requirecache">#</a></span><a aria-hidden="true" class="legacy" id="modules_require_cache"></a></h5>
921<div class="api_metadata">
922<span>Added in: v0.3.0</span>
923</div>
924<ul>
925<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
926</ul>
927<p>Modules are cached in this object when they are required. By deleting a key
928value from this object, the next <code>require</code> will reload the module.
929This does not apply to <a href="addons.html">native addons</a>, for which reloading will result in an
930error.</p>
931<p>Adding or replacing entries is also possible. This cache is checked before
932built-in modules and if a name matching a built-in module is added to the cache,
933only <code>node:</code>-prefixed require calls are going to receive the built-in module.
934Use with care!</p>
935<!-- eslint-disable node-core/no-duplicate-requires -->
936<pre><code class="language-js"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
937<span class="hljs-keyword">const</span> realFs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
938
939<span class="hljs-keyword">const</span> fakeFs = {};
940<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 };
941
942assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>), fakeFs);
943assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>), realFs);</code> <button class="copy-button">copy</button></pre>
944<h5><code>require.extensions</code><span><a class="mark" href="#requireextensions" id="requireextensions">#</a></span><a aria-hidden="true" class="legacy" id="modules_require_extensions"></a></h5>
945<div class="api_metadata">
946<span>Added in: v0.3.0</span><span>Deprecated since: v0.10.6</span>
947</div>
948<p></p><div class="api_stability api_stability_0"><a href="documentation.html#stability-index">Stability: 0</a> - Deprecated</div><p></p>
949<ul>
950<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
951</ul>
952<p>Instruct <code>require</code> on how to handle certain file extensions.</p>
953<p>Process files with the extension <code>.sjs</code> as <code>.js</code>:</p>
954<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> <button class="copy-button">copy</button></pre>
955<p><strong>Deprecated.</strong> In the past, this list has been used to load non-JavaScript
956modules into Node.js by compiling them on-demand. However, in practice, there
957are much better ways to do this, such as loading modules via some other Node.js
958program, or compiling them to JavaScript ahead of time.</p>
959<p>Avoid using <code>require.extensions</code>. Use could cause subtle bugs and resolving the
960extensions gets slower with each registered extension.</p>
961<h5><code>require.main</code><span><a class="mark" href="#requiremain" id="requiremain">#</a></span><a aria-hidden="true" class="legacy" id="modules_require_main"></a></h5>
962<div class="api_metadata">
963<span>Added in: v0.1.17</span>
964</div>
965<ul>
966<li><a href="modules.html#the-module-object" class="type">&#x3C;module></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></li>
967</ul>
968<p>The <code>Module</code> object representing the entry script loaded when the Node.js
969process launched, or <code>undefined</code> if the entry point of the program is not a
970CommonJS module.
971See <a href="#accessing-the-main-module">"Accessing the main module"</a>.</p>
972<p>In <code>entry.js</code> script:</p>
973<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> <button class="copy-button">copy</button></pre>
974<pre><code class="language-bash">node entry.js</code> <button class="copy-button">copy</button></pre>
975<!-- eslint-skip -->
976<pre><code class="language-js"><span class="hljs-title class_">Module</span> {
977  <span class="hljs-attr">id</span>: <span class="hljs-string">'.'</span>,
978  <span class="hljs-attr">path</span>: <span class="hljs-string">'/absolute/path/to'</span>,
979  <span class="hljs-attr">exports</span>: {},
980  <span class="hljs-attr">filename</span>: <span class="hljs-string">'/absolute/path/to/entry.js'</span>,
981  <span class="hljs-attr">loaded</span>: <span class="hljs-literal">false</span>,
982  <span class="hljs-attr">children</span>: [],
983  <span class="hljs-attr">paths</span>:
984   [ <span class="hljs-string">'/absolute/path/to/node_modules'</span>,
985     <span class="hljs-string">'/absolute/path/node_modules'</span>,
986     <span class="hljs-string">'/absolute/node_modules'</span>,
987     <span class="hljs-string">'/node_modules'</span> ] }</code> <button class="copy-button">copy</button></pre>
988<h5><code>require.resolve(request[, options])</code><span><a class="mark" href="#requireresolverequest-options" id="requireresolverequest-options">#</a></span><a aria-hidden="true" class="legacy" id="modules_require_resolve_request_options"></a></h5>
989<div class="api_metadata">
990<details class="changelog"><summary>History</summary>
991<table>
992<tbody><tr><th>Version</th><th>Changes</th></tr>
993<tr><td>v8.9.0</td>
994<td><p>The <code>paths</code> option is now supported.</p></td></tr>
995<tr><td>v0.3.0</td>
996<td><p><span>Added in: v0.3.0</span></p></td></tr>
997</tbody></table>
998</details>
999</div>
1000<ul>
1001<li><code>request</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The module path to resolve.</li>
1002<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
1003<ul>
1004<li><code>paths</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> Paths to resolve module location from. If present, these
1005paths are used instead of the default resolution paths, with the exception
1006of <a href="#loading-from-the-global-folders">GLOBAL_FOLDERS</a> like <code>$HOME/.node_modules</code>, which are
1007always included. Each of these paths is used as a starting point for
1008the module resolution algorithm, meaning that the <code>node_modules</code> hierarchy
1009is checked from this location.</li>
1010</ul>
1011</li>
1012<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
1013</ul>
1014<p>Use the internal <code>require()</code> machinery to look up the location of a module,
1015but rather than loading the module, just return the resolved filename.</p>
1016<p>If the module can not be found, a <code>MODULE_NOT_FOUND</code> error is thrown.</p>
1017<h6><code>require.resolve.paths(request)</code><span><a class="mark" href="#requireresolvepathsrequest" id="requireresolvepathsrequest">#</a></span><a aria-hidden="true" class="legacy" id="modules_require_resolve_paths_request"></a></h6>
1018<div class="api_metadata">
1019<span>Added in: v8.9.0</span>
1020</div>
1021<ul>
1022<li><code>request</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The module path whose lookup paths are being retrieved.</li>
1023<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a></li>
1024</ul>
1025<p>Returns an array containing the paths searched during resolution of <code>request</code> or
1026<code>null</code> if the <code>request</code> string references a core module, for example <code>http</code> or
1027<code>fs</code>.</p>
1028</section><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="modules_the_module_object"></a></h3>
1029<div class="api_metadata">
1030<span>Added in: v0.1.16</span>
1031</div>
1032
1033
1034<ul>
1035<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
1036</ul>
1037<p>In each module, the <code>module</code> free variable is a reference to the object
1038representing the current module. For convenience, <code>module.exports</code> is
1039also accessible via the <code>exports</code> module-global. <code>module</code> is not actually
1040a global but rather local to each module.</p>
1041<h4><code>module.children</code><span><a class="mark" href="#modulechildren" id="modulechildren">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_children"></a></h4>
1042<div class="api_metadata">
1043<span>Added in: v0.1.16</span>
1044</div>
1045<ul>
1046<li><a href="modules.html#the-module-object" class="type">&#x3C;module[]></a></li>
1047</ul>
1048<p>The module objects required for the first time by this one.</p>
1049<h4><code>module.exports</code><span><a class="mark" href="#moduleexports" id="moduleexports">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_exports"></a></h4>
1050<div class="api_metadata">
1051<span>Added in: v0.1.16</span>
1052</div>
1053<ul>
1054<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
1055</ul>
1056<p>The <code>module.exports</code> object is created by the <code>Module</code> system. Sometimes this is
1057not acceptable; many want their module to be an instance of some class. To do
1058this, assign the desired export object to <code>module.exports</code>. Assigning
1059the desired object to <code>exports</code> will simply rebind the local <code>exports</code> variable,
1060which is probably not what is desired.</p>
1061<p>For example, suppose we were making a module called <code>a.js</code>:</p>
1062<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">'node:events'</span>);
1063
1064<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>();
1065
1066<span class="hljs-comment">// Do some work, and after some time emit</span>
1067<span class="hljs-comment">// the 'ready' event from the module itself.</span>
1068<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
1069  <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>);
1070}, <span class="hljs-number">1000</span>);</code> <button class="copy-button">copy</button></pre>
1071<p>Then in another file we could do:</p>
1072<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>);
1073a.<span class="hljs-title function_">on</span>(<span class="hljs-string">'ready'</span>, <span class="hljs-function">() =></span> {
1074  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'module "a" is ready'</span>);
1075});</code> <button class="copy-button">copy</button></pre>
1076<p>Assignment to <code>module.exports</code> must be done immediately. It cannot be
1077done in any callbacks. This does not work:</p>
1078<p><code>x.js</code>:</p>
1079<pre><code class="language-js"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
1080  <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> };
1081}, <span class="hljs-number">0</span>);</code> <button class="copy-button">copy</button></pre>
1082<p><code>y.js</code>:</p>
1083<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>);
1084<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x.<span class="hljs-property">a</span>);</code> <button class="copy-button">copy</button></pre>
1085<h5><code>exports</code> shortcut<span><a class="mark" href="#exports-shortcut" id="exports-shortcut">#</a></span><a aria-hidden="true" class="legacy" id="modules_exports_shortcut"></a></h5>
1086<div class="api_metadata">
1087<span>Added in: v0.1.16</span>
1088</div>
1089<p>The <code>exports</code> variable is available within a module's file-level scope, and is
1090assigned the value of <code>module.exports</code> before the module is evaluated.</p>
1091<p>It allows a shortcut, so that <code>module.exports.f = ...</code> can be written more
1092succinctly as <code>exports.f = ...</code>. However, be aware that like any variable, if a
1093new value is assigned to <code>exports</code>, it is no longer bound to <code>module.exports</code>:</p>
1094<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>
1095<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> <button class="copy-button">copy</button></pre>
1096<p>When the <code>module.exports</code> property is being completely replaced by a new
1097object, it is common to also reassign <code>exports</code>:</p>
1098<!-- eslint-disable func-name-matching -->
1099<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>) {
1100  <span class="hljs-comment">// ... etc.</span>
1101};</code> <button class="copy-button">copy</button></pre>
1102<p>To illustrate the behavior, imagine this hypothetical implementation of
1103<code>require()</code>, which is quite similar to what is actually done by <code>require()</code>:</p>
1104<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>) {
1105  <span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = { <span class="hljs-attr">exports</span>: {} };
1106  (<span class="hljs-function">(<span class="hljs-params"><span class="hljs-variable language_">module</span>, <span class="hljs-built_in">exports</span></span>) =></span> {
1107    <span class="hljs-comment">// Module code here. In this example, define a function.</span>
1108    <span class="hljs-keyword">function</span> <span class="hljs-title function_">someFunc</span>(<span class="hljs-params"></span>) {}
1109    <span class="hljs-built_in">exports</span> = someFunc;
1110    <span class="hljs-comment">// At this point, exports is no longer a shortcut to module.exports, and</span>
1111    <span class="hljs-comment">// this module will still export an empty default object.</span>
1112    <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = someFunc;
1113    <span class="hljs-comment">// At this point, the module will now export someFunc, instead of the</span>
1114    <span class="hljs-comment">// default object.</span>
1115  })(<span class="hljs-variable language_">module</span>, <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>);
1116  <span class="hljs-keyword">return</span> <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>;
1117}</code> <button class="copy-button">copy</button></pre>
1118<h4><code>module.filename</code><span><a class="mark" href="#modulefilename" id="modulefilename">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_filename"></a></h4>
1119<div class="api_metadata">
1120<span>Added in: v0.1.16</span>
1121</div>
1122<ul>
1123<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
1124</ul>
1125<p>The fully resolved filename of the module.</p>
1126<h4><code>module.id</code><span><a class="mark" href="#moduleid" id="moduleid">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_id"></a></h4>
1127<div class="api_metadata">
1128<span>Added in: v0.1.16</span>
1129</div>
1130<ul>
1131<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
1132</ul>
1133<p>The identifier for the module. Typically this is the fully resolved
1134filename.</p>
1135<h4><code>module.isPreloading</code><span><a class="mark" href="#moduleispreloading" id="moduleispreloading">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_ispreloading"></a></h4>
1136<div class="api_metadata">
1137<span>Added in: v15.4.0, v14.17.0</span>
1138</div>
1139<ul>
1140<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>true</code> if the module is running during the Node.js preload
1141phase.</li>
1142</ul>
1143<h4><code>module.loaded</code><span><a class="mark" href="#moduleloaded" id="moduleloaded">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_loaded"></a></h4>
1144<div class="api_metadata">
1145<span>Added in: v0.1.16</span>
1146</div>
1147<ul>
1148<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
1149</ul>
1150<p>Whether or not the module is done loading, or is in the process of
1151loading.</p>
1152<h4><code>module.parent</code><span><a class="mark" href="#moduleparent" id="moduleparent">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_parent"></a></h4>
1153<div class="api_metadata">
1154<span>Added in: v0.1.16</span><span>Deprecated since: v14.6.0, v12.19.0</span>
1155</div>
1156<p></p><div class="api_stability api_stability_0"><a href="documentation.html#stability-index">Stability: 0</a> - Deprecated: Please use <a href="#requiremain"><code>require.main</code></a> and
1157<a href="#modulechildren"><code>module.children</code></a> instead.</div><p></p>
1158<ul>
1159<li><a href="modules.html#the-module-object" class="type">&#x3C;module></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></li>
1160</ul>
1161<p>The module that first required this one, or <code>null</code> if the current module is the
1162entry point of the current process, or <code>undefined</code> if the module was loaded by
1163something that is not a CommonJS module (E.G.: REPL or <code>import</code>).</p>
1164<h4><code>module.path</code><span><a class="mark" href="#modulepath" id="modulepath">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_path"></a></h4>
1165<div class="api_metadata">
1166<span>Added in: v11.14.0</span>
1167</div>
1168<ul>
1169<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
1170</ul>
1171<p>The directory name of the module. This is usually the same as the
1172<a href="path.html#pathdirnamepath"><code>path.dirname()</code></a> of the <a href="#moduleid"><code>module.id</code></a>.</p>
1173<h4><code>module.paths</code><span><a class="mark" href="#modulepaths" id="modulepaths">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_paths"></a></h4>
1174<div class="api_metadata">
1175<span>Added in: v0.4.0</span>
1176</div>
1177<ul>
1178<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
1179</ul>
1180<p>The search paths for the module.</p>
1181<h4><code>module.require(id)</code><span><a class="mark" href="#modulerequireid" id="modulerequireid">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_require_id"></a></h4>
1182<div class="api_metadata">
1183<span>Added in: v0.5.1</span>
1184</div>
1185<ul>
1186<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
1187<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> exported module content</li>
1188</ul>
1189<p>The <code>module.require()</code> method provides a way to load a module as if
1190<code>require()</code> was called from the original module.</p>
1191<p>In order to do this, it is necessary to get a reference to the <code>module</code> object.
1192Since <code>require()</code> returns the <code>module.exports</code>, and the <code>module</code> is typically
1193<em>only</em> available within a specific module's code, it must be explicitly exported
1194in order to be used.</p>
1195</section><section><h3>The <code>Module</code> object<span><a class="mark" href="#the-module-object_1" id="the-module-object_1">#</a></span><a aria-hidden="true" class="legacy" id="modules_the_module_object_1"></a></h3>
1196<p>This section was moved to
1197<a href="module.html#the-module-object">Modules: <code>module</code> core module</a>.</p>
1198<!-- Anchors to make sure old links find a target -->
1199<ul>
1200<li><a id="modules_module_builtinmodules" href="module.html#modulebuiltinmodules"><code>module.builtinModules</code></a></li>
1201<li><a id="modules_module_createrequire_filename" href="module.html#modulecreaterequirefilename"><code>module.createRequire(filename)</code></a></li>
1202<li><a id="modules_module_syncbuiltinesmexports" href="module.html#modulesyncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a></li>
1203</ul>
1204</section><section><h3>Source map v3 support<span><a class="mark" href="#source-map-v3-support" id="source-map-v3-support">#</a></span><a aria-hidden="true" class="legacy" id="modules_source_map_v3_support"></a></h3>
1205<p>This section was moved to
1206<a href="module.html#source-map-v3-support">Modules: <code>module</code> core module</a>.</p>
1207<!-- Anchors to make sure old links find a target -->
1208<ul>
1209<li><a id="modules_module_findsourcemap_path_error" href="module.html#modulefindsourcemappath"><code>module.findSourceMap(path)</code></a></li>
1210<li><a id="modules_class_module_sourcemap" href="module.html#class-modulesourcemap">Class: <code>module.SourceMap</code></a>
1211<ul>
1212<li><a id="modules_new_sourcemap_payload" href="module.html#new-sourcemappayload"><code>new SourceMap(payload)</code></a></li>
1213<li><a id="modules_sourcemap_payload" href="module.html#sourcemappayload"><code>sourceMap.payload</code></a></li>
1214<li><a id="modules_sourcemap_findentry_linenumber_columnnumber" href="module.html#sourcemapfindentrylinenumber-columnnumber"><code>sourceMap.findEntry(lineNumber, columnNumber)</code></a></li>
1215</ul>
1216</li>
1217</ul></section>
1218        <!-- API END -->
1219      </div>
1220    </div>
1221  </div>
1222</body>
1223</html>
1224