File: module.html

package info (click to toggle)
nodejs 20.19.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 219,072 kB
  • sloc: cpp: 1,277,408; javascript: 565,332; ansic: 129,476; python: 58,536; sh: 3,841; makefile: 2,725; asm: 1,732; perl: 248; lisp: 222; xml: 42
file content (1332 lines) | stat: -rw-r--r-- 106,895 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <meta name="nodejs.org:node-version" content="v20.19.2">
  <title>Modules: node:module API | Node.js v20.19.2 Documentation</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback">
  <link rel="stylesheet" href="assets/style.css">
  <link rel="stylesheet" href="assets/hljs.css">
  <link rel="canonical" href="https://nodejs.org/api/module.html">
  <script async defer src="assets/api.js" type="text/javascript"></script>
  <script>
      const storedTheme = localStorage.getItem('theme');

      // Follow operating system theme preference
      if (storedTheme === null && window.matchMedia) {
        const mq = window.matchMedia('(prefers-color-scheme: dark)');
        if (mq.matches) {
          document.documentElement.classList.add('dark-mode');
        }
      } else if (storedTheme === 'dark') {
        document.documentElement.classList.add('dark-mode');
      }
  </script>
  <style>@media(max-width:430px){.with-26-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:574px){.with-44-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:590px){.with-46-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:646px){.with-53-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}</style>
</head>
<body class="alt apidoc" id="api-section-module">
  <a href="#apicontent" class="skip-to-content">Skip to content</a>
  <div id="content" class="clearfix">
    <div role="navigation" id="column2" class="interior">
      <div id="intro" class="interior">
        <a href="/" title="Go back to the home page">
          Node.js
        </a>
      </div>
      <ul>
<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
</ul>
<hr class="line">
<ul>
<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
<li><a href="console.html" class="nav-console">Console</a></li>
<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
<li><a href="dns.html" class="nav-dns">DNS</a></li>
<li><a href="domain.html" class="nav-domain">Domain</a></li>
<li><a href="errors.html" class="nav-errors">Errors</a></li>
<li><a href="events.html" class="nav-events">Events</a></li>
<li><a href="fs.html" class="nav-fs">File system</a></li>
<li><a href="globals.html" class="nav-globals">Globals</a></li>
<li><a href="http.html" class="nav-http">HTTP</a></li>
<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
<li><a href="https.html" class="nav-https">HTTPS</a></li>
<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
<li><a href="module.html" class="nav-module active">Modules: <code>node:module</code> API</a></li>
<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
<li><a href="net.html" class="nav-net">Net</a></li>
<li><a href="os.html" class="nav-os">OS</a></li>
<li><a href="path.html" class="nav-path">Path</a></li>
<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
<li><a href="process.html" class="nav-process">Process</a></li>
<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
<li><a href="readline.html" class="nav-readline">Readline</a></li>
<li><a href="repl.html" class="nav-repl">REPL</a></li>
<li><a href="report.html" class="nav-report">Report</a></li>
<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
<li><a href="stream.html" class="nav-stream">Stream</a></li>
<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
<li><a href="test.html" class="nav-test">Test runner</a></li>
<li><a href="timers.html" class="nav-timers">Timers</a></li>
<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
<li><a href="tty.html" class="nav-tty">TTY</a></li>
<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
<li><a href="url.html" class="nav-url">URL</a></li>
<li><a href="util.html" class="nav-util">Utilities</a></li>
<li><a href="v8.html" class="nav-v8">V8</a></li>
<li><a href="vm.html" class="nav-vm">VM</a></li>
<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
</ul>
<hr class="line">
<ul>
<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
</ul>
    </div>

    <div id="column1" data-id="module" class="interior">
      <header class="header">
        <div class="header-container">
          <h1>Node.js v20.19.2 documentation</h1>
          <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden>
            <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24">
              <path fill="none" d="M0 0h24v24H0z" />
              <path d="M11.1 12.08c-2.33-4.51-.5-8.48.53-10.07C6.27 2.2 1.98 6.59 1.98 12c0 .14.02.28.02.42.62-.27 1.29-.42 2-.42 1.66 0 3.18.83 4.1 2.15A4.01 4.01 0 0111 18c0 1.52-.87 2.83-2.12 3.51.98.32 2.03.5 3.11.5 3.5 0 6.58-1.8 8.37-4.52-2.36.23-6.98-.97-9.26-5.41z"/>
              <path d="M7 16h-.18C6.4 14.84 5.3 14 4 14c-1.66 0-3 1.34-3 3s1.34 3 3 3h3c1.1 0 2-.9 2-2s-.9-2-2-2z"/>
            </svg>
            <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24">
              <path d="M0 0h24v24H0z" fill="none" />
              <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/>
            </svg>
          </button>
        </div>
        <div id="gtoc">
          <ul>
            <li class="pinned-header">Node.js v20.19.2</li>
            
    <li class="picker-header">
      <a href="#toc-picker" aria-controls="toc-picker">
        <span class="picker-arrow"></span>
        Table of contents
      </a>

      <div class="picker" tabindex="-1"><div class="toc"><ul id="toc-picker">
<li><a href="#modules-nodemodule-api">Modules: <code>node:module</code> API</a>
<ul>
<li><a href="#the-module-object">The <code>Module</code> object</a>
<ul>
<li><a href="#modulebuiltinmodules"><code>module.builtinModules</code></a></li>
<li><a href="#modulecreaterequirefilename"><code>module.createRequire(filename)</code></a></li>
<li><a href="#moduleisbuiltinmodulename"><code>module.isBuiltin(moduleName)</code></a></li>
<li><span class="stability_1"><a href="#moduleregisterspecifier-parenturl-options"><code>module.register(specifier[, parentURL][, options])</code></a></span></li>
<li><a href="#modulesyncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#customization-hooks">Customization Hooks</a></span>
<ul>
<li><a href="#enabling">Enabling</a></li>
<li><a href="#chaining">Chaining</a></li>
<li><a href="#communication-with-module-customization-hooks">Communication with module customization hooks</a></li>
<li><a href="#hooks">Hooks</a>
<ul>
<li><span class="stability_1"><a href="#initialize"><code>initialize()</code></a></span></li>
<li><span class="stability_1"><a href="#resolvespecifier-context-nextresolve"><code>resolve(specifier, context, nextResolve)</code></a></span></li>
<li><span class="stability_1"><a href="#loadurl-context-nextload"><code>load(url, context, nextLoad)</code></a></span></li>
<li><span class="stability_1"><a href="#globalpreload"><code>globalPreload()</code></a></span></li>
</ul>
</li>
<li><a href="#examples">Examples</a>
<ul>
<li><a href="#import-from-https">Import from HTTPS</a></li>
<li><a href="#transpilation">Transpilation</a></li>
<li><a href="#import-maps">Import maps</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_1"><a href="#source-map-v3-support">Source map v3 support</a></span>
<ul>
<li><a href="#modulefindsourcemappath"><code>module.findSourceMap(path)</code></a></li>
<li><a href="#class-modulesourcemap">Class: <code>module.SourceMap</code></a>
<ul>
<li><a href="#new-sourcemappayload--linelengths-"><code>new SourceMap(payload[, { lineLengths }])</code></a></li>
<li><a href="#sourcemappayload"><code>sourceMap.payload</code></a></li>
<li><a href="#sourcemapfindentrylineoffset-columnoffset"><code>sourceMap.findEntry(lineOffset, columnOffset)</code></a></li>
<li><a href="#sourcemapfindoriginlinenumber-columnnumber"><code>sourceMap.findOrigin(lineNumber, columnNumber)</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul></div></div>
    </li>
  
            
    <li class="picker-header">
      <a href="#gtoc-picker" aria-controls="gtoc-picker">
        <span class="picker-arrow"></span>
        Index
      </a>

      <div class="picker" tabindex="-1" id="gtoc-picker"><ul>
<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>

      <li>
        <a href="index.html">Index</a>
      </li>
    </ul>
  
<hr class="line">
<ul>
<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
<li><a href="console.html" class="nav-console">Console</a></li>
<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
<li><a href="dns.html" class="nav-dns">DNS</a></li>
<li><a href="domain.html" class="nav-domain">Domain</a></li>
<li><a href="errors.html" class="nav-errors">Errors</a></li>
<li><a href="events.html" class="nav-events">Events</a></li>
<li><a href="fs.html" class="nav-fs">File system</a></li>
<li><a href="globals.html" class="nav-globals">Globals</a></li>
<li><a href="http.html" class="nav-http">HTTP</a></li>
<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
<li><a href="https.html" class="nav-https">HTTPS</a></li>
<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
<li><a href="module.html" class="nav-module active">Modules: <code>node:module</code> API</a></li>
<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
<li><a href="net.html" class="nav-net">Net</a></li>
<li><a href="os.html" class="nav-os">OS</a></li>
<li><a href="path.html" class="nav-path">Path</a></li>
<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
<li><a href="process.html" class="nav-process">Process</a></li>
<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
<li><a href="readline.html" class="nav-readline">Readline</a></li>
<li><a href="repl.html" class="nav-repl">REPL</a></li>
<li><a href="report.html" class="nav-report">Report</a></li>
<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
<li><a href="stream.html" class="nav-stream">Stream</a></li>
<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
<li><a href="test.html" class="nav-test">Test runner</a></li>
<li><a href="timers.html" class="nav-timers">Timers</a></li>
<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
<li><a href="tty.html" class="nav-tty">TTY</a></li>
<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
<li><a href="url.html" class="nav-url">URL</a></li>
<li><a href="util.html" class="nav-util">Utilities</a></li>
<li><a href="v8.html" class="nav-v8">V8</a></li>
<li><a href="vm.html" class="nav-vm">VM</a></li>
<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
</ul>
<hr class="line">
<ul>
<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
</ul></div>
    </li>
  
            
    <li class="picker-header">
      <a href="#alt-docs" aria-controls="alt-docs">
        <span class="picker-arrow"></span>
        Other versions
      </a>
      <div class="picker" tabindex="-1"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v24.x/api/module.html">24.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v23.x/api/module.html">23.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v22.x/api/module.html">22.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v21.x/api/module.html">21.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v20.x/api/module.html">20.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v19.x/api/module.html">19.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v18.x/api/module.html">18.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v17.x/api/module.html">17.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v16.x/api/module.html">16.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v15.x/api/module.html">15.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v14.x/api/module.html">14.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v13.x/api/module.html">13.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v12.x/api/module.html">12.x</a></li></ol></div>
    </li>
  
            <li class="picker-header">
              <a href="#options-picker" aria-controls="options-picker">
                <span class="picker-arrow"></span>
                Options
              </a>
        
              <div class="picker" tabindex="-1">
                <ul id="options-picker">
                  <li>
                    <a href="all.html">View on single page</a>
                  </li>
                  <li>
                    <a href="module.json">View as JSON</a>
                  </li>
                  <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/main/doc/api/module.md">Edit on GitHub</a></li>    
                </ul>
              </div>
            </li>
          </ul>
        </div>
        <hr>
      </header>

      <details role="navigation" id="toc" open><summary>Table of contents</summary><ul>
<li><a href="#modules-nodemodule-api">Modules: <code>node:module</code> API</a>
<ul>
<li><a href="#the-module-object">The <code>Module</code> object</a>
<ul>
<li><a href="#modulebuiltinmodules"><code>module.builtinModules</code></a></li>
<li><a href="#modulecreaterequirefilename"><code>module.createRequire(filename)</code></a></li>
<li><a href="#moduleisbuiltinmodulename"><code>module.isBuiltin(moduleName)</code></a></li>
<li><span class="stability_1"><a href="#moduleregisterspecifier-parenturl-options"><code>module.register(specifier[, parentURL][, options])</code></a></span></li>
<li><a href="#modulesyncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#customization-hooks">Customization Hooks</a></span>
<ul>
<li><a href="#enabling">Enabling</a></li>
<li><a href="#chaining">Chaining</a></li>
<li><a href="#communication-with-module-customization-hooks">Communication with module customization hooks</a></li>
<li><a href="#hooks">Hooks</a>
<ul>
<li><span class="stability_1"><a href="#initialize"><code>initialize()</code></a></span></li>
<li><span class="stability_1"><a href="#resolvespecifier-context-nextresolve"><code>resolve(specifier, context, nextResolve)</code></a></span></li>
<li><span class="stability_1"><a href="#loadurl-context-nextload"><code>load(url, context, nextLoad)</code></a></span></li>
<li><span class="stability_1"><a href="#globalpreload"><code>globalPreload()</code></a></span></li>
</ul>
</li>
<li><a href="#examples">Examples</a>
<ul>
<li><a href="#import-from-https">Import from HTTPS</a></li>
<li><a href="#transpilation">Transpilation</a></li>
<li><a href="#import-maps">Import maps</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_1"><a href="#source-map-v3-support">Source map v3 support</a></span>
<ul>
<li><a href="#modulefindsourcemappath"><code>module.findSourceMap(path)</code></a></li>
<li><a href="#class-modulesourcemap">Class: <code>module.SourceMap</code></a>
<ul>
<li><a href="#new-sourcemappayload--linelengths-"><code>new SourceMap(payload[, { lineLengths }])</code></a></li>
<li><a href="#sourcemappayload"><code>sourceMap.payload</code></a></li>
<li><a href="#sourcemapfindentrylineoffset-columnoffset"><code>sourceMap.findEntry(lineOffset, columnOffset)</code></a></li>
<li><a href="#sourcemapfindoriginlinenumber-columnnumber"><code>sourceMap.findOrigin(lineNumber, columnNumber)</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul></details>

      <div role="main" id="apicontent">
        <h2>Modules: <code>node:module</code> API<span><a class="mark" href="#modules-nodemodule-api" id="modules-nodemodule-api">#</a></span><a aria-hidden="true" class="legacy" id="module_modules_node_module_api"></a></h2>

<div class="api_metadata">
<span>Added in: v0.3.7</span>
</div>
<section><h3>The <code>Module</code> object<span><a class="mark" href="#the-module-object" id="the-module-object">#</a></span><a aria-hidden="true" class="legacy" id="module_the_module_object"></a></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Provides general utility methods when interacting with instances of
<code>Module</code>, the <a href="modules.html#the-module-object"><code>module</code></a> variable often seen in <a href="modules.html">CommonJS</a> modules. Accessed
via <code>import 'node:module'</code> or <code>require('node:module')</code>.</p>
<h4><code>module.builtinModules</code><span><a class="mark" href="#modulebuiltinmodules" id="modulebuiltinmodules">#</a></span><a aria-hidden="true" class="legacy" id="module_module_builtinmodules"></a></h4>
<div class="api_metadata">
<span>Added in: v9.3.0, v8.10.0, v6.13.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>A list of the names of all modules provided by Node.js. Can be used to verify
if a module is maintained by a third party or not.</p>
<p>Note: the list doesn't contain <a href="modules.html#built-in-modules-with-mandatory-node-prefix">prefix-only modules</a> like <code>node:test</code>.</p>
<p><code>module</code> in this context isn't the same object that's provided
by the <a href="modules.html#the-module-wrapper">module wrapper</a>. To access it, require the <code>Module</code> module:</p>

<pre class="with-26-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// module.mjs</span>
<span class="hljs-comment">// In an ECMAScript module</span>
<span class="hljs-keyword">import</span> { builtinModules <span class="hljs-keyword">as</span> builtin } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;</code><code class="language-js cjs"><span class="hljs-comment">// module.cjs</span>
<span class="hljs-comment">// In a CommonJS module</span>
<span class="hljs-keyword">const</span> builtin = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>).<span class="hljs-property">builtinModules</span>;</code><button class="copy-button">copy</button></pre>
<h4><code>module.createRequire(filename)</code><span><a class="mark" href="#modulecreaterequirefilename" id="modulecreaterequirefilename">#</a></span><a aria-hidden="true" class="legacy" id="module_module_createrequire_filename"></a></h4>
<div class="api_metadata">
<span>Added in: v12.2.0</span>
</div>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="url.html#the-whatwg-url-api" class="type">&#x3C;URL></a> Filename to be used to construct the require
function. Must be a file URL object, file URL string, or absolute path
string.</li>
<li>Returns: <a href="modules.html#requireid" class="type">&#x3C;require></a> Require function</li>
</ul>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { createRequire } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
<span class="hljs-keyword">const</span> <span class="hljs-built_in">require</span> = <span class="hljs-title function_">createRequire</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);

<span class="hljs-comment">// sibling-module.js is a CommonJS module.</span>
<span class="hljs-keyword">const</span> siblingModule = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./sibling-module'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>module.isBuiltin(moduleName)</code><span><a class="mark" href="#moduleisbuiltinmodulename" id="moduleisbuiltinmodulename">#</a></span><a aria-hidden="true" class="legacy" id="module_module_isbuiltin_modulename"></a></h4>
<div class="api_metadata">
<span>Added in: v18.6.0, v16.17.0</span>
</div>
<ul>
<li><code>moduleName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> name of the module</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> returns true if the module is builtin else returns false</li>
</ul>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { isBuiltin } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
<span class="hljs-title function_">isBuiltin</span>(<span class="hljs-string">'node:fs'</span>); <span class="hljs-comment">// true</span>
<span class="hljs-title function_">isBuiltin</span>(<span class="hljs-string">'fs'</span>); <span class="hljs-comment">// true</span>
<span class="hljs-title function_">isBuiltin</span>(<span class="hljs-string">'wss'</span>); <span class="hljs-comment">// false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>module.register(specifier[, parentURL][, options])</code><span><a class="mark" href="#moduleregisterspecifier-parenturl-options" id="moduleregisterspecifier-parenturl-options">#</a></span><a aria-hidden="true" class="legacy" id="module_module_register_specifier_parenturl_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.2</td>
<td><p>Using this feature with the permission model enabled requires passing <code>--allow-worker</code>.</p></td></tr>
<tr><td>v20.8.0</td>
<td><p>Add support for WHATWG URL instances.</p></td></tr>
<tr><td>v20.6.0</td>
<td><p><span>Added in: v20.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
<ul>
<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="url.html#the-whatwg-url-api" class="type">&#x3C;URL></a> Customization hooks to be registered; this should be
the same string that would be passed to <code>import()</code>, except that if it is
relative, it is resolved relative to <code>parentURL</code>.</li>
<li><code>parentURL</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="url.html#the-whatwg-url-api" class="type">&#x3C;URL></a> If you want to resolve <code>specifier</code> relative to a base
URL, such as <code>import.meta.url</code>, you can pass that URL here. <strong>Default:</strong>
<code>'data:'</code></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>parentURL</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="url.html#the-whatwg-url-api" class="type">&#x3C;URL></a> If you want to resolve <code>specifier</code> relative to a
base URL, such as <code>import.meta.url</code>, you can pass that URL here. This
property is ignored if the <code>parentURL</code> is supplied as the second argument.
<strong>Default:</strong> <code>'data:'</code></li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Any arbitrary, cloneable JavaScript value to pass into the
<a href="#initialize"><code>initialize</code></a> hook.</li>
<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a> <a href="worker_threads.html#portpostmessagevalue-transferlist">transferrable objects</a> to be passed into the
<code>initialize</code> hook.</li>
</ul>
</li>
</ul>
<p>Register a module that exports <a href="#customization-hooks">hooks</a> that customize Node.js module
resolution and loading behavior. See <a href="#customization-hooks">Customization hooks</a>.</p>
<p>This feature requires <code>--allow-worker</code> if used with the <a href="permissions.html#permission-model">Permission Model</a>.</p>
<h4><code>module.syncBuiltinESMExports()</code><span><a class="mark" href="#modulesyncbuiltinesmexports" id="modulesyncbuiltinesmexports">#</a></span><a aria-hidden="true" class="legacy" id="module_module_syncbuiltinesmexports"></a></h4>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<p>The <code>module.syncBuiltinESMExports()</code> method updates all the live bindings for
builtin <a href="esm.html">ES Modules</a> to match the properties of the <a href="modules.html">CommonJS</a> exports. It
does not add or remove exported names from the <a href="esm.html">ES Modules</a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { syncBuiltinESMExports } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);

fs.<span class="hljs-property">readFile</span> = newAPI;

<span class="hljs-keyword">delete</span> fs.<span class="hljs-property">readFileSync</span>;

<span class="hljs-keyword">function</span> <span class="hljs-title function_">newAPI</span>(<span class="hljs-params"></span>) {
  <span class="hljs-comment">// ...</span>
}

fs.<span class="hljs-property">newAPI</span> = newAPI;

<span class="hljs-title function_">syncBuiltinESMExports</span>();

<span class="hljs-keyword">import</span>(<span class="hljs-string">'node:fs'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">esmFS</span>) =></span> {
  <span class="hljs-comment">// It syncs the existing readFile property with the new value</span>
  assert.<span class="hljs-title function_">strictEqual</span>(esmFS.<span class="hljs-property">readFile</span>, newAPI);
  <span class="hljs-comment">// readFileSync has been deleted from the required fs</span>
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-string">'readFileSync'</span> <span class="hljs-keyword">in</span> fs, <span class="hljs-literal">false</span>);
  <span class="hljs-comment">// syncBuiltinESMExports() does not remove readFileSync from esmFS</span>
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-string">'readFileSync'</span> <span class="hljs-keyword">in</span> esmFS, <span class="hljs-literal">true</span>);
  <span class="hljs-comment">// syncBuiltinESMExports() does not add names</span>
  assert.<span class="hljs-title function_">strictEqual</span>(esmFS.<span class="hljs-property">newAPI</span>, <span class="hljs-literal">undefined</span>);
});</code> <button class="copy-button">copy</button></pre>
<p><i id="module_customization_hooks"></i></p>
</section><section><h3>Customization Hooks<span><a class="mark" href="#customization-hooks" id="customization-hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_customization_hooks"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.6.0</td>
<td><p>Added <code>initialize</code> hook to replace <code>globalPreload</code>.</p></td></tr>
<tr><td>v18.6.0, v16.17.0</td>
<td><p>Add support for chaining loaders.</p></td></tr>
<tr><td>v16.12.0</td>
<td><p>Removed <code>getFormat</code>, <code>getSource</code>, <code>transformSource</code>, and <code>globalPreload</code>; added <code>load</code> hook and <code>getGlobalPreload</code> hook.</p></td></tr>
<tr><td>v8.8.0</td>
<td><p><span>Added in: v8.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>

<p><i id="enabling_module_customization_hooks"></i></p>
<h4>Enabling<span><a class="mark" href="#enabling" id="enabling">#</a></span><a aria-hidden="true" class="legacy" id="module_enabling"></a></h4>
<p>Module resolution and loading can be customized by registering a file which
exports a set of hooks. This can be done using the <a href="#moduleregisterspecifier-parenturl-options"><code>register</code></a> method
from <code>node:module</code>, which you can run before your application code by
using the <code>--import</code> flag:</p>
<pre><code class="language-bash">node --import ./register-hooks.js ./my-app.js</code> <button class="copy-button">copy</button></pre>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// register-hooks.js</span>
<span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;

<span class="hljs-title function_">register</span>(<span class="hljs-string">'./hooks.mjs'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);</code><code class="language-js cjs"><span class="hljs-comment">// register-hooks.js</span>
<span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);

<span class="hljs-title function_">register</span>(<span class="hljs-string">'./hooks.mjs'</span>, <span class="hljs-title function_">pathToFileURL</span>(__filename));</code><button class="copy-button">copy</button></pre>
<p>The file passed to <code>--import</code> can also be an export from a dependency:</p>
<pre><code class="language-bash">node --import some-package/register ./my-app.js</code> <button class="copy-button">copy</button></pre>
<p>Where <code>some-package</code> has an <a href="packages.html#exports"><code>"exports"</code></a> field defining the <code>/register</code>
export to map to a file that calls <code>register()</code>, like the following <code>register-hooks.js</code>
example.</p>
<p>Using <code>--import</code> ensures that the hooks are registered before any application
files are imported, including the entry point of the application. Alternatively,
<code>register</code> can be called from the entry point, but dynamic <code>import()</code> must be
used for any code that should be run after the hooks are registered:</p>

<pre class="with-46-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;

<span class="hljs-title function_">register</span>(<span class="hljs-string">'http-to-https'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);

<span class="hljs-comment">// Because this is a dynamic `import()`, the `http-to-https` hooks will run</span>
<span class="hljs-comment">// to handle `./my-app.js` and any other files it imports or requires.</span>
<span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.js'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);

<span class="hljs-title function_">register</span>(<span class="hljs-string">'http-to-https'</span>, <span class="hljs-title function_">pathToFileURL</span>(__filename));

<span class="hljs-comment">// Because this is a dynamic `import()`, the `http-to-https` hooks will run</span>
<span class="hljs-comment">// to handle `./my-app.js` and any other files it imports or requires.</span>
<span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.js'</span>);</code><button class="copy-button">copy</button></pre>
<p>In this example, we are registering the <code>http-to-https</code> hooks, but they will
only be available for subsequently imported modules—in this case, <code>my-app.js</code>
and anything it references via <code>import</code> (and optionally <code>require</code>). If the
<code>import('./my-app.js')</code> had instead been a static <code>import './my-app.js'</code>, the
app would have <em>already</em> been loaded <strong>before</strong> the <code>http-to-https</code> hooks were
registered. This due to the ES modules specification, where static imports are
evaluated from the leaves of the tree first, then back to the trunk. There can
be static imports <em>within</em> <code>my-app.js</code>, which will not be evaluated until
<code>my-app.js</code> is dynamically imported.</p>
<p><code>my-app.js</code> can also be CommonJS. Customization hooks will run for any
modules that it references via <code>import</code> (and optionally <code>require</code>).</p>
<p>Finally, if all you want to do is register hooks before your app runs and you
don't want to create a separate file for that purpose, you can pass a <code>data:</code>
URL to <code>--import</code>:</p>
<pre><code class="language-bash">node --import <span class="hljs-string">'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register("http-to-https", pathToFileURL("./"));'</span> ./my-app.js</code> <button class="copy-button">copy</button></pre>
<h4>Chaining<span><a class="mark" href="#chaining" id="chaining">#</a></span><a aria-hidden="true" class="legacy" id="module_chaining"></a></h4>
<p>It's possible to call <code>register</code> more than once:</p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// entrypoint.mjs</span>
<span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;

<span class="hljs-title function_">register</span>(<span class="hljs-string">'./foo.mjs'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
<span class="hljs-title function_">register</span>(<span class="hljs-string">'./bar.mjs'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
<span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.mjs'</span>);</code><code class="language-js cjs"><span class="hljs-comment">// entrypoint.cjs</span>
<span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);

<span class="hljs-keyword">const</span> parentURL = <span class="hljs-title function_">pathToFileURL</span>(__filename);
<span class="hljs-title function_">register</span>(<span class="hljs-string">'./foo.mjs'</span>, parentURL);
<span class="hljs-title function_">register</span>(<span class="hljs-string">'./bar.mjs'</span>, parentURL);
<span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.mjs'</span>);</code><button class="copy-button">copy</button></pre>
<p>In this example, the registered hooks will form chains. These chains run
last-in, first out (LIFO). If both <code>foo.mjs</code> and <code>bar.mjs</code> define a <code>resolve</code>
hook, they will be called like so (note the right-to-left):
node's default ← <code>./foo.mjs</code> ← <code>./bar.mjs</code>
(starting with <code>./bar.mjs</code>, then <code>./foo.mjs</code>, then the Node.js default).
The same applies to all the other hooks.</p>
<p>The registered hooks also affect <code>register</code> itself. In this example,
<code>bar.mjs</code> will be resolved and loaded via the hooks registered by <code>foo.mjs</code>
(because <code>foo</code>'s hooks will have already been added to the chain). This allows
for things like writing hooks in non-JavaScript languages, so long as
earlier registered hooks transpile into JavaScript.</p>
<p>The <code>register</code> method cannot be called from within the module that defines the
hooks.</p>
<h4>Communication with module customization hooks<span><a class="mark" href="#communication-with-module-customization-hooks" id="communication-with-module-customization-hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_communication_with_module_customization_hooks"></a></h4>
<p>Module customization hooks run on a dedicated thread, separate from the main
thread that runs application code. This means mutating global variables won't
affect the other thread(s), and message channels must be used to communicate
between the threads.</p>
<p>The <code>register</code> method can be used to pass data to an <a href="#initialize"><code>initialize</code></a> hook. The
data passed to the hook may include transferrable objects like ports.</p>

<pre class="with-53-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">MessageChannel</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;

<span class="hljs-comment">// This example demonstrates how a message channel can be used to</span>
<span class="hljs-comment">// communicate with the hooks, by sending `port2` to the hooks.</span>
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(msg);
});
port1.<span class="hljs-title function_">unref</span>();

<span class="hljs-title function_">register</span>(<span class="hljs-string">'./my-hooks.mjs'</span>, {
  <span class="hljs-attr">parentURL</span>: <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>,
  <span class="hljs-attr">data</span>: { <span class="hljs-attr">number</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">port</span>: port2 },
  <span class="hljs-attr">transferList</span>: [port2],
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-comment">// This example showcases how a message channel can be used to</span>
<span class="hljs-comment">// communicate with the hooks, by sending `port2` to the hooks.</span>
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(msg);
});
port1.<span class="hljs-title function_">unref</span>();

<span class="hljs-title function_">register</span>(<span class="hljs-string">'./my-hooks.mjs'</span>, {
  <span class="hljs-attr">parentURL</span>: <span class="hljs-title function_">pathToFileURL</span>(__filename),
  <span class="hljs-attr">data</span>: { <span class="hljs-attr">number</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">port</span>: port2 },
  <span class="hljs-attr">transferList</span>: [port2],
});</code><button class="copy-button">copy</button></pre>
<h4>Hooks<span><a class="mark" href="#hooks" id="hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_hooks"></a></h4>
<p>The <a href="#moduleregisterspecifier-parenturl-options"><code>register</code></a> method can be used to register a module that exports a set of
hooks. The hooks are functions that are called by Node.js to customize the
module resolution and loading process. The exported functions must have specific
names and signatures, and they must be exported as named exports.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">initialize</span>(<span class="hljs-params">{ number, port }</span>) {
  <span class="hljs-comment">// Receives data from `register`.</span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) {
  <span class="hljs-comment">// Take an `import` or `require` specifier and resolve it to a URL.</span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
  <span class="hljs-comment">// Take a resolved URL and return the source code to be evaluated.</span>
}</code> <button class="copy-button">copy</button></pre>
<p>Hooks are part of a <a href="#chaining">chain</a>, even if that chain consists of only one
custom (user-provided) hook and the default hook, which is always present. Hook
functions nest: each one must always return a plain object, and chaining happens
as a result of each function calling <code>next&#x3C;hookName>()</code>, which is a reference to
the subsequent loader's hook (in LIFO order).</p>
<p>A hook that returns a value lacking a required property triggers an exception. A
hook that returns without calling <code>next&#x3C;hookName>()</code> <em>and</em> without returning
<code>shortCircuit: true</code> also triggers an exception. These errors are to help
prevent unintentional breaks in the chain. Return <code>shortCircuit: true</code> from a
hook to signal that the chain is intentionally ending at your hook.</p>
<p>Hooks are run in a separate thread, isolated from the main thread where
application code runs. That means it is a different <a href="https://tc39.es/ecma262/#realm">realm</a>. The hooks thread
may be terminated by the main thread at any time, so do not depend on
asynchronous operations (like <code>console.log</code>) to complete.</p>
<h5><code>initialize()</code><span><a class="mark" href="#initialize" id="initialize">#</a></span><a aria-hidden="true" class="legacy" id="module_initialize"></a></h5>
<div class="api_metadata">
<span>Added in: v20.6.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The data from <code>register(loader, import.meta.url, { data })</code>.</li>
</ul>
<p>The <code>initialize</code> hook provides a way to define a custom function that runs in
the hooks thread when the hooks module is initialized. Initialization happens
when the hooks module is registered via <a href="#moduleregisterspecifier-parenturl-options"><code>register</code></a>.</p>
<p>This hook can receive data from a <a href="#moduleregisterspecifier-parenturl-options"><code>register</code></a> invocation, including
ports and other transferrable objects. The return value of <code>initialize</code> can be a
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a>, in which case it will be awaited before the main application thread
execution resumes.</p>
<p>Module customization code:</p>
<pre><code class="language-js mjs"><span class="hljs-comment">// path-to-my-hooks.js</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">initialize</span>(<span class="hljs-params">{ number, port }</span>) {
  port.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">`increment: <span class="hljs-subst">${number + <span class="hljs-number">1</span>}</span>`</span>);
}</code> <button class="copy-button">copy</button></pre>
<p>Caller code:</p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">MessageChannel</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;

<span class="hljs-comment">// This example showcases how a message channel can be used to communicate</span>
<span class="hljs-comment">// between the main (application) thread and the hooks running on the hooks</span>
<span class="hljs-comment">// thread, by sending `port2` to the `initialize` hook.</span>
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
  assert.<span class="hljs-title function_">strictEqual</span>(msg, <span class="hljs-string">'increment: 2'</span>);
});
port1.<span class="hljs-title function_">unref</span>();

<span class="hljs-title function_">register</span>(<span class="hljs-string">'./path-to-my-hooks.js'</span>, {
  <span class="hljs-attr">parentURL</span>: <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>,
  <span class="hljs-attr">data</span>: { <span class="hljs-attr">number</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">port</span>: port2 },
  <span class="hljs-attr">transferList</span>: [port2],
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-comment">// This example showcases how a message channel can be used to communicate</span>
<span class="hljs-comment">// between the main (application) thread and the hooks running on the hooks</span>
<span class="hljs-comment">// thread, by sending `port2` to the `initialize` hook.</span>
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
  assert.<span class="hljs-title function_">strictEqual</span>(msg, <span class="hljs-string">'increment: 2'</span>);
});
port1.<span class="hljs-title function_">unref</span>();

<span class="hljs-title function_">register</span>(<span class="hljs-string">'./path-to-my-hooks.js'</span>, {
  <span class="hljs-attr">parentURL</span>: <span class="hljs-title function_">pathToFileURL</span>(__filename),
  <span class="hljs-attr">data</span>: { <span class="hljs-attr">number</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">port</span>: port2 },
  <span class="hljs-attr">transferList</span>: [port2],
});</code><button class="copy-button">copy</button></pre>
<h5><code>resolve(specifier, context, nextResolve)</code><span><a class="mark" href="#resolvespecifier-context-nextresolve" id="resolvespecifier-context-nextresolve">#</a></span><a aria-hidden="true" class="legacy" id="module_resolve_specifier_context_nextresolve"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.0</td>
<td><p>The property <code>context.importAssertions</code> is replaced with <code>context.importAttributes</code>. Using the old name is still supported and will emit an experimental warning.</p></td></tr>
<tr><td>v18.6.0, v16.17.0</td>
<td><p>Add support for chaining resolve hooks. Each hook must either call <code>nextResolve()</code> or include a <code>shortCircuit</code> property set to <code>true</code> in its return.</p></td></tr>
<tr><td>v17.1.0, v16.14.0</td>
<td><p>Add support for import assertions.</p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
<ul>
<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>conditions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> Export conditions of the relevant <code>package.json</code></li>
<li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An object whose key-value pairs represent the
attributes for the module to import</li>
<li><code>parentURL</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The module importing this one, or undefined
if this is the Node.js entry point</li>
</ul>
</li>
<li><code>nextResolve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The subsequent <code>resolve</code> hook in the chain, or the
Node.js default <code>resolve</code> hook after the last user-supplied <code>resolve</code> hook
<ul>
<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a>
<ul>
<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> A hint to the load hook (it might be
ignored)
<code>'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'</code></li>
<li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The import attributes to use when
caching the module (optional; if excluded the input will be used)</li>
<li><code>shortCircuit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> A signal that this hook intends to
terminate the chain of <code>resolve</code> hooks. <strong>Default:</strong> <code>false</code></li>
<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The absolute URL to which this input resolves</li>
</ul>
</li>
</ul>
<blockquote>
<p><strong>Warning</strong> Despite support for returning promises and async functions, calls
to <code>resolve</code> may block the main thread which can impact performance.</p>
</blockquote>
<p>The <code>resolve</code> hook chain is responsible for telling Node.js where to find and
how to cache a given <code>import</code> statement or expression, or <code>require</code> call. It can
optionally return a format (such as <code>'module'</code>) as a hint to the <code>load</code> hook. If
a format is specified, the <code>load</code> hook is ultimately responsible for providing
the final <code>format</code> value (and it is free to ignore the hint provided by
<code>resolve</code>); if <code>resolve</code> provides a <code>format</code>, a custom <code>load</code> hook is required
even if only to pass the value to the Node.js default <code>load</code> hook.</p>
<p>Import type attributes are part of the cache key for saving loaded modules into
the internal module cache. The <code>resolve</code> hook is responsible for returning an
<code>importAttributes</code> object if the module should be cached with different
attributes than were present in the source code.</p>
<p>The <code>conditions</code> property in <code>context</code> is an array of conditions for
<a href="packages.html#conditional-exports">package exports conditions</a> that apply to this resolution
request. They can be used for looking up conditional mappings elsewhere or to
modify the list when calling the default resolution logic.</p>
<p>The current <a href="packages.html#conditional-exports">package exports conditions</a> are always in
the <code>context.conditions</code> array passed into the hook. To guarantee <em>default
Node.js module specifier resolution behavior</em> when calling <code>defaultResolve</code>, the
<code>context.conditions</code> array passed to it <em>must</em> include <em>all</em> elements of the
<code>context.conditions</code> array originally passed into the <code>resolve</code> hook.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) {
  <span class="hljs-keyword">const</span> { parentURL = <span class="hljs-literal">null</span> } = context;

  <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() > <span class="hljs-number">0.5</span>) { <span class="hljs-comment">// Some condition.</span>
    <span class="hljs-comment">// For some or all specifiers, do some custom logic for resolving.</span>
    <span class="hljs-comment">// Always return an object of the form {url: &#x3C;string>}.</span>
    <span class="hljs-keyword">return</span> {
      <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">url</span>: parentURL ?
        <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(specifier, parentURL).<span class="hljs-property">href</span> :
        <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(specifier).<span class="hljs-property">href</span>,
    };
  }

  <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() &#x3C; <span class="hljs-number">0.5</span>) { <span class="hljs-comment">// Another condition.</span>
    <span class="hljs-comment">// When calling `defaultResolve`, the arguments can be modified. In this</span>
    <span class="hljs-comment">// case it's adding another value for matching conditional exports.</span>
    <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier, {
      ...context,
      <span class="hljs-attr">conditions</span>: [...context.<span class="hljs-property">conditions</span>, <span class="hljs-string">'another-condition'</span>],
    });
  }

  <span class="hljs-comment">// Defer to the next hook in the chain, which would be the</span>
  <span class="hljs-comment">// Node.js default resolve if this is the last user-specified loader.</span>
  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier);
}</code> <button class="copy-button">copy</button></pre>
<h5><code>load(url, context, nextLoad)</code><span><a class="mark" href="#loadurl-context-nextload" id="loadurl-context-nextload">#</a></span><a aria-hidden="true" class="legacy" id="module_load_url_context_nextload"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.6.0</td>
<td><p>Add support for <code>source</code> with format <code>commonjs</code>.</p></td></tr>
<tr><td>v18.6.0, v16.17.0</td>
<td><p>Add support for chaining load hooks. Each hook must either call <code>nextLoad()</code> or include a <code>shortCircuit</code> property set to <code>true</code> in its return.</p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
<ul>
<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The URL returned by the <code>resolve</code> chain</li>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>conditions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> Export conditions of the relevant <code>package.json</code></li>
<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The format optionally supplied by the
<code>resolve</code> hook chain</li>
<li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
</li>
<li><code>nextLoad</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The subsequent <code>load</code> hook in the chain, or the
Node.js default <code>load</code> hook after the last user-supplied <code>load</code> hook
<ul>
<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>shortCircuit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> A signal that this hook intends to
terminate the chain of <code>load</code> hooks. <strong>Default:</strong> <code>false</code></li>
<li><code>source</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> The source for Node.js to evaluate</li>
</ul>
</li>
</ul>
<p>The <code>load</code> hook provides a way to define a custom method of determining how a
URL should be interpreted, retrieved, and parsed. It is also in charge of
validating the import assertion.</p>
<p>The final value of <code>format</code> must be one of the following:</p>



































<table><thead><tr><th><code>format</code></th><th>Description</th><th>Acceptable types for <code>source</code> returned by <code>load</code></th></tr></thead><tbody><tr><td><code>'builtin'</code></td><td>Load a Node.js builtin module</td><td>Not applicable</td></tr><tr><td><code>'commonjs'</code></td><td>Load a Node.js CommonJS module</td><td>{ <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String"><code>string</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>, <code>null</code>, <code>undefined</code> }</td></tr><tr><td><code>'json'</code></td><td>Load a JSON file</td><td>{ <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String"><code>string</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> }</td></tr><tr><td><code>'module'</code></td><td>Load an ES module</td><td>{ <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String"><code>string</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> }</td></tr><tr><td><code>'wasm'</code></td><td>Load a WebAssembly module</td><td>{ <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> }</td></tr></tbody></table>
<p>The value of <code>source</code> is ignored for type <code>'builtin'</code> because currently it is
not possible to replace the value of a Node.js builtin (core) module.</p>
<p>Omitting vs providing a <code>source</code> for <code>'commonjs'</code> has very different effects:</p>
<ul>
<li>When a <code>source</code> is provided, all <code>require</code> calls from this module will be
processed by the ESM loader with registered <code>resolve</code> and <code>load</code> hooks; all
<code>require.resolve</code> calls from this module will be processed by the ESM loader
with registered <code>resolve</code> hooks; only a subset of the CommonJS API will be
available (e.g. no <code>require.extensions</code>, no <code>require.cache</code>, no
<code>require.resolve.paths</code>) and monkey-patching on the CommonJS module loader
will not apply.</li>
<li>If <code>source</code> is undefined or <code>null</code>, it will be handled by the CommonJS module
loader and <code>require</code>/<code>require.resolve</code> calls will not go through the
registered hooks. This behavior for nullish <code>source</code> is temporary — in the
future, nullish <code>source</code> will not be supported.</li>
</ul>
<p>When <code>node</code> is run with <code>--experimental-default-type=commonjs</code>, the Node.js
internal <code>load</code> implementation, which is the value of <code>next</code> for the
last hook in the <code>load</code> chain, returns <code>null</code> for <code>source</code> when <code>format</code> is
<code>'commonjs'</code> for backward compatibility. Here is an example hook that would
opt-in to using the non-default behavior:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
  <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> <span class="hljs-title function_">nextLoad</span>(url, context);
  <span class="hljs-keyword">if</span> (result.<span class="hljs-property">format</span> === <span class="hljs-string">'commonjs'</span>) {
    result.<span class="hljs-property">source</span> ??= <span class="hljs-keyword">await</span> <span class="hljs-title function_">readFile</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(result.<span class="hljs-property">responseURL</span> ?? url));
  }
  <span class="hljs-keyword">return</span> result;
}</code> <button class="copy-button">copy</button></pre>
<blockquote>
<p><strong>Warning</strong>: The ESM <code>load</code> hook and namespaced exports from CommonJS modules
are incompatible. Attempting to use them together will result in an empty
object from the import. This may be addressed in the future.</p>
</blockquote>
<blockquote>
<p>These types all correspond to classes defined in ECMAScript.</p>
</blockquote>
<ul>
<li>The specific <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> object is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a>.</li>
<li>The specific <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> object is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a>.</li>
</ul>
<p>If the source value of a text-based format (i.e., <code>'json'</code>, <code>'module'</code>)
is not a string, it is converted to a string using <a href="util.html#class-utiltextdecoder"><code>util.TextDecoder</code></a>.</p>
<p>The <code>load</code> hook provides a way to define a custom method for retrieving the
source code of a resolved URL. This would allow a loader to potentially avoid
reading files from disk. It could also be used to map an unrecognized format to
a supported one, for example <code>yaml</code> to <code>module</code>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
  <span class="hljs-keyword">const</span> { format } = context;

  <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() > <span class="hljs-number">0.5</span>) { <span class="hljs-comment">// Some condition</span>
    <span class="hljs-comment">/*
      For some or all URLs, do some custom logic for retrieving the source.
      Always return an object of the form {
        format: &#x3C;string>,
        source: &#x3C;string|buffer>,
      }.
    */</span>
    <span class="hljs-keyword">return</span> {
      format,
      <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">source</span>: <span class="hljs-string">'...'</span>,
    };
  }

  <span class="hljs-comment">// Defer to the next hook in the chain.</span>
  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url);
}</code> <button class="copy-button">copy</button></pre>
<p>In a more advanced scenario, this can also be used to transform an unsupported
source to a supported one (see <a href="#examples">Examples</a> below).</p>
<h5><code>globalPreload()</code><span><a class="mark" href="#globalpreload" id="globalpreload">#</a></span><a aria-hidden="true" class="legacy" id="module_globalpreload"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.6.0, v16.17.0</td>
<td><p>Add support for chaining globalPreload hooks.</p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a>.0 - Early development</div><p></p>
<blockquote>
<p><strong>Warning:</strong> This hook will be removed in a future version. Use
<a href="#initialize"><code>initialize</code></a> instead. When a hooks module has an <code>initialize</code> export,
<code>globalPreload</code> will be ignored.</p>
</blockquote>
<ul>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Information to assist the preload code
<ul>
<li><code>port</code> <a href="worker_threads.html#class-messageport" class="type">&#x3C;MessagePort></a></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Code to run before application startup</li>
</ul>
<p>Sometimes it might be necessary to run some code inside of the same global
scope that the application runs in. This hook allows the return of a string
that is run as a sloppy-mode script on startup.</p>
<p>Similar to how CommonJS wrappers work, the code runs in an implicit function
scope. The only argument is a <code>require</code>-like function that can be used to load
builtins like "fs": <code>getBuiltin(request: string)</code>.</p>
<p>If the code needs more advanced <code>require</code> features, it has to construct
its own <code>require</code> using  <code>module.createRequire()</code>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">globalPreload</span>(<span class="hljs-params">context</span>) {
  <span class="hljs-keyword">return</span> <span class="hljs-string">`\
globalThis.someInjectedProperty = 42;
console.log('I just set some globals!');

const { createRequire } = getBuiltin('module');
const { cwd } = getBuiltin('process');

const require = createRequire(cwd() + '/&#x3C;preload>');
// [...]
`</span>;
}</code> <button class="copy-button">copy</button></pre>
<p>Another argument is provided to the preload code: <code>port</code>. This is available as a
parameter to the hook and inside of the source text returned by the hook. This
functionality has been moved to the <code>initialize</code> hook.</p>
<p>Care must be taken in order to properly call <a href="worker_threads.html#portref"><code>port.ref()</code></a> and
<a href="worker_threads.html#portunref"><code>port.unref()</code></a> to prevent a process from being in a state where it won't
close normally.</p>
<pre><code class="language-js mjs"><span class="hljs-comment">/**
 * This example has the application context send a message to the hook
 * and sends the message back to the application context
 */</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">globalPreload</span>(<span class="hljs-params">{ port }</span>) {
  port.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">evt</span>) =></span> {
    port.<span class="hljs-title function_">postMessage</span>(evt.<span class="hljs-property">data</span>);
  };
  <span class="hljs-keyword">return</span> <span class="hljs-string">`\
    port.postMessage('console.log("I went to the hook and back");');
    port.onmessage = (evt) => {
      eval(evt.data);
    };
  `</span>;
}</code> <button class="copy-button">copy</button></pre>
<h4>Examples<span><a class="mark" href="#examples" id="examples">#</a></span><a aria-hidden="true" class="legacy" id="module_examples"></a></h4>
<p>The various module customization hooks can be used together to accomplish
wide-ranging customizations of the Node.js code loading and evaluation
behaviors.</p>
<h5>Import from HTTPS<span><a class="mark" href="#import-from-https" id="import-from-https">#</a></span><a aria-hidden="true" class="legacy" id="module_import_from_https"></a></h5>
<p>In current Node.js, specifiers starting with <code>https://</code> are experimental (see
<a href="esm.html#https-and-http-imports">HTTPS and HTTP imports</a>).</p>
<p>The hook below registers hooks to enable rudimentary support for such
specifiers. While this may seem like a significant improvement to Node.js core
functionality, there are substantial downsides to actually using these hooks:
performance is much slower than loading files from disk, there is no caching,
and there is no security.</p>
<pre><code class="language-js mjs"><span class="hljs-comment">// https-hooks.mjs</span>
<span class="hljs-keyword">import</span> { get } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:https'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
  <span class="hljs-comment">// For JavaScript to be loaded over the network, we need to fetch and</span>
  <span class="hljs-comment">// return it.</span>
  <span class="hljs-keyword">if</span> (url.<span class="hljs-title function_">startsWith</span>(<span class="hljs-string">'https://'</span>)) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
      <span class="hljs-title function_">get</span>(url, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
        <span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>;
        res.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
        res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> data += chunk);
        res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> <span class="hljs-title function_">resolve</span>({
          <span class="hljs-comment">// This example assumes all network-provided JavaScript is ES module</span>
          <span class="hljs-comment">// code.</span>
          <span class="hljs-attr">format</span>: <span class="hljs-string">'module'</span>,
          <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
          <span class="hljs-attr">source</span>: data,
        }));
      }).<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> <span class="hljs-title function_">reject</span>(err));
    });
  }

  <span class="hljs-comment">// Let Node.js handle all other URLs.</span>
  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url);
}</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js mjs"><span class="hljs-comment">// main.mjs</span>
<span class="hljs-keyword">import</span> { <span class="hljs-variable constant_">VERSION</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'https://coffeescript.org/browser-compiler-modern/coffeescript.js'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-variable constant_">VERSION</span>);</code> <button class="copy-button">copy</button></pre>
<p>With the preceding hooks module, running
<code>node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./https-hooks.mjs"));' ./main.mjs</code>
prints the current version of CoffeeScript per the module at the URL in
<code>main.mjs</code>.</p>
<h5>Transpilation<span><a class="mark" href="#transpilation" id="transpilation">#</a></span><a aria-hidden="true" class="legacy" id="module_transpilation"></a></h5>
<p>Sources that are in formats Node.js doesn't understand can be converted into
JavaScript using the <a href="#loadurl-context-nextload"><code>load</code> hook</a>.</p>
<p>This is less performant than transpiling source files before running Node.js;
transpiler hooks should only be used for development and testing purposes.</p>
<pre><code class="language-js mjs"><span class="hljs-comment">// coffeescript-hooks.mjs</span>
<span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">import</span> { dirname, extname, resolve <span class="hljs-keyword">as</span> resolvePath } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;
<span class="hljs-keyword">import</span> { cwd } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> { fileURLToPath, pathToFileURL } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-keyword">import</span> coffeescript <span class="hljs-keyword">from</span> <span class="hljs-string">'coffeescript'</span>;

<span class="hljs-keyword">const</span> extensionsRegex = <span class="hljs-regexp">/\.(coffee|litcoffee|coffee\.md)$/</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
  <span class="hljs-keyword">if</span> (extensionsRegex.<span class="hljs-title function_">test</span>(url)) {
    <span class="hljs-comment">// CoffeeScript files can be either CommonJS or ES modules, so we want any</span>
    <span class="hljs-comment">// CoffeeScript file to be treated by Node.js the same as a .js file at the</span>
    <span class="hljs-comment">// same location. To determine how Node.js would interpret an arbitrary .js</span>
    <span class="hljs-comment">// file, search up the file system for the nearest parent package.json file</span>
    <span class="hljs-comment">// and read its "type" field.</span>
    <span class="hljs-keyword">const</span> format = <span class="hljs-keyword">await</span> <span class="hljs-title function_">getPackageType</span>(url);

    <span class="hljs-keyword">const</span> { <span class="hljs-attr">source</span>: rawSource } = <span class="hljs-keyword">await</span> <span class="hljs-title function_">nextLoad</span>(url, { ...context, format });
    <span class="hljs-comment">// This hook converts CoffeeScript source code into JavaScript source code</span>
    <span class="hljs-comment">// for all imported CoffeeScript files.</span>
    <span class="hljs-keyword">const</span> transformedSource = coffeescript.<span class="hljs-title function_">compile</span>(rawSource.<span class="hljs-title function_">toString</span>(), url);

    <span class="hljs-keyword">return</span> {
      format,
      <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">source</span>: transformedSource,
    };
  }

  <span class="hljs-comment">// Let Node.js handle all other URLs.</span>
  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url);
}

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getPackageType</span>(<span class="hljs-params">url</span>) {
  <span class="hljs-comment">// `url` is only a file path during the first iteration when passed the</span>
  <span class="hljs-comment">// resolved url from the load() hook</span>
  <span class="hljs-comment">// an actual file path from load() will contain a file extension as it's</span>
  <span class="hljs-comment">// required by the spec</span>
  <span class="hljs-comment">// this simple truthy check for whether `url` contains a file extension will</span>
  <span class="hljs-comment">// work for most projects but does not cover some edge-cases (such as</span>
  <span class="hljs-comment">// extensionless files or a url ending in a trailing space)</span>
  <span class="hljs-keyword">const</span> isFilePath = !!<span class="hljs-title function_">extname</span>(url);
  <span class="hljs-comment">// If it is a file path, get the directory it's in</span>
  <span class="hljs-keyword">const</span> dir = isFilePath ?
    <span class="hljs-title function_">dirname</span>(<span class="hljs-title function_">fileURLToPath</span>(url)) :
    url;
  <span class="hljs-comment">// Compose a file path to a package.json in the same directory,</span>
  <span class="hljs-comment">// which may or may not exist</span>
  <span class="hljs-keyword">const</span> packagePath = <span class="hljs-title function_">resolvePath</span>(dir, <span class="hljs-string">'package.json'</span>);
  <span class="hljs-comment">// Try to read the possibly nonexistent package.json</span>
  <span class="hljs-keyword">const</span> type = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readFile</span>(packagePath, { <span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span> })
    .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">filestring</span>) =></span> <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(filestring).<span class="hljs-property">type</span>)
    .<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
      <span class="hljs-keyword">if</span> (err?.<span class="hljs-property">code</span> !== <span class="hljs-string">'ENOENT'</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
    });
  <span class="hljs-comment">// If package.json existed and contained a `type` field with a value, voilà</span>
  <span class="hljs-keyword">if</span> (type) <span class="hljs-keyword">return</span> type;
  <span class="hljs-comment">// Otherwise, (if not at the root) continue checking the next directory up</span>
  <span class="hljs-comment">// If at the root, stop and return false</span>
  <span class="hljs-keyword">return</span> dir.<span class="hljs-property">length</span> > <span class="hljs-number">1</span> &#x26;&#x26; <span class="hljs-title function_">getPackageType</span>(<span class="hljs-title function_">resolvePath</span>(dir, <span class="hljs-string">'..'</span>));
}</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-coffee"><span class="hljs-comment"># main.coffee</span>
<span class="hljs-keyword">import</span> { scream } <span class="hljs-keyword">from</span> <span class="hljs-string">'./scream.coffee'</span>
console.log scream <span class="hljs-string">'hello, world'</span>

<span class="hljs-keyword">import</span> { version } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>
console.log <span class="hljs-string">"Brought to you by Node.js version <span class="hljs-subst">#{version}</span>"</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-coffee"><span class="hljs-comment"># scream.coffee</span>
<span class="hljs-keyword">export</span> scream = <span class="hljs-function"><span class="hljs-params">(str)</span> -></span> str.toUpperCase()</code> <button class="copy-button">copy</button></pre>
<p>With the preceding hooks module, running
<code>node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./coffeescript-hooks.mjs"));' ./main.coffee</code>
causes <code>main.coffee</code> to be turned into JavaScript after its source code is
loaded from disk but before Node.js executes it; and so on for any <code>.coffee</code>,
<code>.litcoffee</code> or <code>.coffee.md</code> files referenced via <code>import</code> statements of any
loaded file.</p>
<h5>Import maps<span><a class="mark" href="#import-maps" id="import-maps">#</a></span><a aria-hidden="true" class="legacy" id="module_import_maps"></a></h5>
<p>The previous two examples defined <code>load</code> hooks. This is an example of a
<code>resolve</code> hook. This hooks module reads an <code>import-map.json</code> file that defines
which specifiers to override to other URLs (this is a very simplistic
implementation of a small subset of the "import maps" specification).</p>
<pre><code class="language-js mjs"><span class="hljs-comment">// import-map-hooks.js</span>
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">const</span> { imports } = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(<span class="hljs-keyword">await</span> fs.<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'import-map.json'</span>));

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) {
  <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">hasOwn</span>(imports, specifier)) {
    <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(imports[specifier], context);
  }

  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier, context);
}</code> <button class="copy-button">copy</button></pre>
<p>With these files:</p>
<pre><code class="language-js mjs"><span class="hljs-comment">// main.js</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'a-module'</span>;</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-json"><span class="hljs-comment">// import-map.json</span>
<span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"imports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"a-module"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./some-module.js"</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js mjs"><span class="hljs-comment">// some-module.js</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'some module!'</span>);</code> <button class="copy-button">copy</button></pre>
<p>Running <code>node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./import-map-hooks.js"));' main.js</code>
should print <code>some module!</code>.</p>
</section><section><h3>Source map v3 support<span><a class="mark" href="#source-map-v3-support" id="source-map-v3-support">#</a></span><a aria-hidden="true" class="legacy" id="module_source_map_v3_support"></a></h3>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Helpers for interacting with the source map cache. This cache is
populated when source map parsing is enabled and
<a href="https://sourcemaps.info/spec.html#h.lmz475t4mvbx">source map include directives</a> are found in a modules' footer.</p>
<p>To enable source map parsing, Node.js must be run with the flag
<a href="cli.html#--enable-source-maps"><code>--enable-source-maps</code></a>, or with code coverage enabled by setting
<a href="cli.html#node_v8_coveragedir"><code>NODE_V8_COVERAGE=dir</code></a>.</p>

<pre class="with-26-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// module.mjs</span>
<span class="hljs-comment">// In an ECMAScript module</span>
<span class="hljs-keyword">import</span> { findSourceMap, <span class="hljs-title class_">SourceMap</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;</code><code class="language-js cjs"><span class="hljs-comment">// module.cjs</span>
<span class="hljs-comment">// In a CommonJS module</span>
<span class="hljs-keyword">const</span> { findSourceMap, <span class="hljs-title class_">SourceMap</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);</code><button class="copy-button">copy</button></pre>
<!-- Anchors to make sure old links find a target -->
<p><a id="module_module_findsourcemap_path_error"></a></p>
<h4><code>module.findSourceMap(path)</code><span><a class="mark" href="#modulefindsourcemappath" id="modulefindsourcemappath">#</a></span><a aria-hidden="true" class="legacy" id="module_module_findsourcemap_path"></a></h4>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="module.html#class-modulesourcemap" class="type">&#x3C;module.SourceMap></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> Returns <code>module.SourceMap</code> if a source
map is found, <code>undefined</code> otherwise.</li>
</ul>
<p><code>path</code> is the resolved path for the file for which a corresponding source map
should be fetched.</p>
<h4>Class: <code>module.SourceMap</code><span><a class="mark" href="#class-modulesourcemap" id="class-modulesourcemap">#</a></span><a aria-hidden="true" class="legacy" id="module_class_module_sourcemap"></a></h4>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0</span>
</div>
<h5><code>new SourceMap(payload[, { lineLengths }])</code><span><a class="mark" href="#new-sourcemappayload--linelengths-" id="new-sourcemappayload--linelengths-">#</a></span><a aria-hidden="true" class="legacy" id="module_new_sourcemap_payload_linelengths"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.5.0</td>
<td><p>Add support for <code>lineLengths</code>.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>payload</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
<li><code>lineLengths</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number[]></a></li>
</ul>
<p>Creates a new <code>sourceMap</code> instance.</p>
<p><code>payload</code> is an object with keys matching the <a href="https://sourcemaps.info/spec.html#h.mofvlxcwqzej">Source map v3 format</a>:</p>
<ul>
<li><code>file</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>version</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>sources</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
<li><code>sourcesContent</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
<li><code>names</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
<li><code>mappings</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>sourceRoot</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p><code>lineLengths</code> is an optional array of the length of each line in the
generated code.</p>
<h5><code>sourceMap.payload</code><span><a class="mark" href="#sourcemappayload" id="sourcemappayload">#</a></span><a aria-hidden="true" class="legacy" id="module_sourcemap_payload"></a></h5>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Getter for the payload used to construct the <a href="#class-modulesourcemap"><code>SourceMap</code></a> instance.</p>
<h5><code>sourceMap.findEntry(lineOffset, columnOffset)</code><span><a class="mark" href="#sourcemapfindentrylineoffset-columnoffset" id="sourcemapfindentrylineoffset-columnoffset">#</a></span><a aria-hidden="true" class="legacy" id="module_sourcemap_findentry_lineoffset_columnoffset"></a></h5>
<ul>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The zero-indexed line number offset in
the generated source</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The zero-indexed column number offset
in the generated source</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Given a line offset and column offset in the generated source
file, returns an object representing the SourceMap range in the
original file if found, or an empty object if not.</p>
<p>The object returned contains the following keys:</p>
<ul>
<li>generatedLine: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The line offset of the start of the
range in the generated source</li>
<li>generatedColumn: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The column offset of start of the
range in the generated source</li>
<li>originalSource: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The file name of the original source,
as reported in the SourceMap</li>
<li>originalLine: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The line offset of the start of the
range in the original source</li>
<li>originalColumn: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The column offset of start of the
range in the original source</li>
<li>name: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The returned value represents the raw range as it appears in the
SourceMap, based on zero-indexed offsets, <em>not</em> 1-indexed line and
column numbers as they appear in Error messages and CallSite
objects.</p>
<p>To get the corresponding 1-indexed line and column numbers from a
lineNumber and columnNumber as they are reported by Error stacks
and CallSite objects, use <code>sourceMap.findOrigin(lineNumber, columnNumber)</code></p>
<h5><code>sourceMap.findOrigin(lineNumber, columnNumber)</code><span><a class="mark" href="#sourcemapfindoriginlinenumber-columnnumber" id="sourcemapfindoriginlinenumber-columnnumber">#</a></span><a aria-hidden="true" class="legacy" id="module_sourcemap_findorigin_linenumber_columnnumber"></a></h5>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<ul>
<li><code>lineNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The 1-indexed line number of the call
site in the generated source</li>
<li><code>columnNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The 1-indexed column number
of the call site in the generated source</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Given a 1-indexed <code>lineNumber</code> and <code>columnNumber</code> from a call site in
the generated source, find the corresponding call site location
in the original source.</p>
<p>If the <code>lineNumber</code> and <code>columnNumber</code> provided are not found in any
source map, then an empty object is returned. Otherwise, the
returned object contains the following keys:</p>
<ul>
<li>name: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The name of the range in the
source map, if one was provided</li>
<li>fileName: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The file name of the original source, as
reported in the SourceMap</li>
<li>lineNumber: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The 1-indexed lineNumber of the
corresponding call site in the original source</li>
<li>columnNumber: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The 1-indexed columnNumber of the
corresponding call site in the original source</li>
</ul></section>
        <!-- API END -->
      </div>
    </div>
  </div>
</body>
</html>