-
Notifications
You must be signed in to change notification settings - Fork 30.9k
/
Copy pathmodule.md
1803 lines (1452 loc) Β· 62.4 KB
/
module.md
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
# Modules: `node:module` API
<!--introduced_in=v12.20.0-->
<!-- YAML
added: v0.3.7
-->
## The `Module` object
* {Object}
Provides general utility methods when interacting with instances of
`Module`, the [`module`][] variable often seen in [CommonJS][] modules. Accessed
via `import 'node:module'` or `require('node:module')`.
### `module.builtinModules`
<!-- YAML
added:
- v9.3.0
- v8.10.0
- v6.13.0
changes:
- version: v23.5.0
pr-url: https://github.com/nodejs/node/pull/56185
description: The list now also contains prefix-only modules.
-->
* {string\[]}
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.
`module` in this context isn't the same object that's provided
by the [module wrapper][]. To access it, require the `Module` module:
```mjs
// module.mjs
// In an ECMAScript module
import { builtinModules as builtin } from 'node:module';
```
```cjs
// module.cjs
// In a CommonJS module
const builtin = require('node:module').builtinModules;
```
### `module.createRequire(filename)`
<!-- YAML
added: v12.2.0
-->
* `filename` {string|URL} Filename to be used to construct the require
function. Must be a file URL object, file URL string, or absolute path
string.
* Returns: {require} Require function
```mjs
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
// sibling-module.js is a CommonJS module.
const siblingModule = require('./sibling-module');
```
### `module.findPackageJSON(specifier[, base])`
<!-- YAML
added:
- v23.2.0
- v22.14.0
-->
> Stability: 1.1 - Active Development
* `specifier` {string|URL} The specifier for the module whose `package.json` to
retrieve. When passing a _bare specifier_, the `package.json` at the root of
the package is returned. When passing a _relative specifier_ or an _absolute specifier_,
the closest parent `package.json` is returned.
* `base` {string|URL} The absolute location (`file:` URL string or FS path) of the
containing module. For CJS, use `__filename` (not `__dirname`!); for ESM, use
`import.meta.url`. You do not need to pass it if `specifier` is an `absolute specifier`.
* Returns: {string|undefined} A path if the `package.json` is found. When `specifier`
is a package, the package's root `package.json`; when a relative or unresolved, the closest
`package.json` to the `specifier`.
> **Caveat**: Do not use this to try to determine module format. There are many things affecting
> that determination; the `type` field of package.json is the _least_ definitive (ex file extension
> supersedes it, and a loader hook supersedes that).
> **Caveat**: This currently leverages only the built-in default resolver; if
> [`resolve` customization hooks][resolve hook] are registered, they will not affect the resolution.
> This may change in the future.
```text
/path/to/project
β packages/
β bar/
β bar.js
β package.json // name = '@foo/bar'
β qux/
β node_modules/
β some-package/
β package.json // name = 'some-package'
β qux.js
β package.json // name = '@foo/qux'
β main.js
β package.json // name = '@foo'
```
```mjs
// /path/to/project/packages/bar/bar.js
import { findPackageJSON } from 'node:module';
findPackageJSON('..', import.meta.url);
// '/path/to/project/package.json'
// Same result when passing an absolute specifier instead:
findPackageJSON(new URL('../', import.meta.url));
findPackageJSON(import.meta.resolve('../'));
findPackageJSON('some-package', import.meta.url);
// '/path/to/project/packages/bar/node_modules/some-package/package.json'
// When passing an absolute specifier, you might get a different result if the
// resolved module is inside a subfolder that has nested `package.json`.
findPackageJSON(import.meta.resolve('some-package'));
// '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json'
findPackageJSON('@foo/qux', import.meta.url);
// '/path/to/project/packages/qux/package.json'
```
```cjs
// /path/to/project/packages/bar/bar.js
const { findPackageJSON } = require('node:module');
const { pathToFileURL } = require('node:url');
const path = require('node:path');
findPackageJSON('..', __filename);
// '/path/to/project/package.json'
// Same result when passing an absolute specifier instead:
findPackageJSON(pathToFileURL(path.join(__dirname, '..')));
findPackageJSON('some-package', __filename);
// '/path/to/project/packages/bar/node_modules/some-package/package.json'
// When passing an absolute specifier, you might get a different result if the
// resolved module is inside a subfolder that has nested `package.json`.
findPackageJSON(pathToFileURL(require.resolve('some-package')));
// '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json'
findPackageJSON('@foo/qux', __filename);
// '/path/to/project/packages/qux/package.json'
```
### `module.isBuiltin(moduleName)`
<!-- YAML
added:
- v18.6.0
- v16.17.0
-->
* `moduleName` {string} name of the module
* Returns: {boolean} returns true if the module is builtin else returns false
```mjs
import { isBuiltin } from 'node:module';
isBuiltin('node:fs'); // true
isBuiltin('fs'); // true
isBuiltin('wss'); // false
```
### `module.register(specifier[, parentURL][, options])`
<!-- YAML
added:
- v20.6.0
- v18.19.0
changes:
- version:
- v23.6.1
- v22.13.1
- v20.18.2
pr-url: https://github.com/nodejs-private/node-private/pull/629
description: Using this feature with the permission model enabled requires
passing `--allow-worker`.
- version:
- v20.8.0
- v18.19.0
pr-url: https://github.com/nodejs/node/pull/49655
description: Add support for WHATWG URL instances.
-->
> Stability: 1.2 - Release candidate
* `specifier` {string|URL} Customization hooks to be registered; this should be
the same string that would be passed to `import()`, except that if it is
relative, it is resolved relative to `parentURL`.
* `parentURL` {string|URL} If you want to resolve `specifier` relative to a base
URL, such as `import.meta.url`, you can pass that URL here. **Default:**
`'data:'`
* `options` {Object}
* `parentURL` {string|URL} If you want to resolve `specifier` relative to a
base URL, such as `import.meta.url`, you can pass that URL here. This
property is ignored if the `parentURL` is supplied as the second argument.
**Default:** `'data:'`
* `data` {any} Any arbitrary, cloneable JavaScript value to pass into the
[`initialize`][] hook.
* `transferList` {Object\[]} [transferable objects][] to be passed into the
`initialize` hook.
Register a module that exports [hooks][] that customize Node.js module
resolution and loading behavior. See [Customization hooks][].
This feature requires `--allow-worker` if used with the [Permission Model][].
### `module.registerHooks(options)`
<!-- YAML
added: v23.5.0
-->
> Stability: 1.1 - Active development
* `options` {Object}
* `load` {Function|undefined} See [load hook][]. **Default:** `undefined`.
* `resolve` {Function|undefined} See [resolve hook][]. **Default:** `undefined`.
Register [hooks][] that customize Node.js module resolution and loading behavior.
See [Customization hooks][].
### `module.stripTypeScriptTypes(code[, options])`
<!-- YAML
added:
- v23.2.0
- v22.13.0
-->
> Stability: 1.1 - Active development
* `code` {string} The code to strip type annotations from.
* `options` {Object}
* `mode` {string} **Default:** `'strip'`. Possible values are:
* `'strip'` Only strip type annotations without performing the transformation of TypeScript features.
* `'transform'` Strip type annotations and transform TypeScript features to JavaScript.
* `sourceMap` {boolean} **Default:** `false`. Only when `mode` is `'transform'`, if `true`, a source map
will be generated for the transformed code.
* `sourceUrl` {string} Specifies the source url used in the source map.
* Returns: {string} The code with type annotations stripped.
`module.stripTypeScriptTypes()` removes type annotations from TypeScript code. It
can be used to strip type annotations from TypeScript code before running it
with `vm.runInContext()` or `vm.compileFunction()`.
By default, it will throw an error if the code contains TypeScript features
that require transformation such as `Enums`,
see [type-stripping][] for more information.
When mode is `'transform'`, it also transforms TypeScript features to JavaScript,
see [transform TypeScript features][] for more information.
When mode is `'strip'`, source maps are not generated, because locations are preserved.
If `sourceMap` is provided, when mode is `'strip'`, an error will be thrown.
_WARNING_: The output of this function should not be considered stable across Node.js versions,
due to changes in the TypeScript parser.
```mjs
import { stripTypeScriptTypes } from 'node:module';
const code = 'const a: number = 1;';
const strippedCode = stripTypeScriptTypes(code);
console.log(strippedCode);
// Prints: const a = 1;
```
```cjs
const { stripTypeScriptTypes } = require('node:module');
const code = 'const a: number = 1;';
const strippedCode = stripTypeScriptTypes(code);
console.log(strippedCode);
// Prints: const a = 1;
```
If `sourceUrl` is provided, it will be used appended as a comment at the end of the output:
```mjs
import { stripTypeScriptTypes } from 'node:module';
const code = 'const a: number = 1;';
const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' });
console.log(strippedCode);
// Prints: const a = 1\n\n//# sourceURL=source.ts;
```
```cjs
const { stripTypeScriptTypes } = require('node:module');
const code = 'const a: number = 1;';
const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' });
console.log(strippedCode);
// Prints: const a = 1\n\n//# sourceURL=source.ts;
```
When `mode` is `'transform'`, the code is transformed to JavaScript:
```mjs
import { stripTypeScriptTypes } from 'node:module';
const code = `
namespace MathUtil {
export const add = (a: number, b: number) => a + b;
}`;
const strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true });
console.log(strippedCode);
// Prints:
// var MathUtil;
// (function(MathUtil) {
// MathUtil.add = (a, b)=>a + b;
// })(MathUtil || (MathUtil = {}));
// # sourceMappingURL=data:application/json;base64, ...
```
```cjs
const { stripTypeScriptTypes } = require('node:module');
const code = `
namespace MathUtil {
export const add = (a: number, b: number) => a + b;
}`;
const strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true });
console.log(strippedCode);
// Prints:
// var MathUtil;
// (function(MathUtil) {
// MathUtil.add = (a, b)=>a + b;
// })(MathUtil || (MathUtil = {}));
// # sourceMappingURL=data:application/json;base64, ...
```
### `module.syncBuiltinESMExports()`
<!-- YAML
added: v12.12.0
-->
The `module.syncBuiltinESMExports()` method updates all the live bindings for
builtin [ES Modules][] to match the properties of the [CommonJS][] exports. It
does not add or remove exported names from the [ES Modules][].
```js
const fs = require('node:fs');
const assert = require('node:assert');
const { syncBuiltinESMExports } = require('node:module');
fs.readFile = newAPI;
delete fs.readFileSync;
function newAPI() {
// ...
}
fs.newAPI = newAPI;
syncBuiltinESMExports();
import('node:fs').then((esmFS) => {
// It syncs the existing readFile property with the new value
assert.strictEqual(esmFS.readFile, newAPI);
// readFileSync has been deleted from the required fs
assert.strictEqual('readFileSync' in fs, false);
// syncBuiltinESMExports() does not remove readFileSync from esmFS
assert.strictEqual('readFileSync' in esmFS, true);
// syncBuiltinESMExports() does not add names
assert.strictEqual(esmFS.newAPI, undefined);
});
```
## Module compile cache
<!-- YAML
added: v22.1.0
changes:
- version: v22.8.0
pr-url: https://github.com/nodejs/node/pull/54501
description: add initial JavaScript APIs for runtime access.
-->
The module compile cache can be enabled either using the [`module.enableCompileCache()`][]
method or the [`NODE_COMPILE_CACHE=dir`][] environment variable. After it is enabled,
whenever Node.js compiles a CommonJS or a ECMAScript Module, it will use on-disk
[V8 code cache][] persisted in the specified directory to speed up the compilation.
This may slow down the first load of a module graph, but subsequent loads of the same module
graph may get a significant speedup if the contents of the modules do not change.
To clean up the generated compile cache on disk, simply remove the cache directory. The cache
directory will be recreated the next time the same directory is used for for compile cache
storage. To avoid filling up the disk with stale cache, it is recommended to use a directory
under the [`os.tmpdir()`][]. If the compile cache is enabled by a call to
[`module.enableCompileCache()`][] without specifying the directory, Node.js will use
the [`NODE_COMPILE_CACHE=dir`][] environment variable if it's set, or defaults
to `path.join(os.tmpdir(), 'node-compile-cache')` otherwise. To locate the compile cache
directory used by a running Node.js instance, use [`module.getCompileCacheDir()`][].
Currently when using the compile cache with [V8 JavaScript code coverage][], the
coverage being collected by V8 may be less precise in functions that are
deserialized from the code cache. It's recommended to turn this off when
running tests to generate precise coverage.
The enabled module compile cache can be disabled by the [`NODE_DISABLE_COMPILE_CACHE=1`][]
environment variable. This can be useful when the compile cache leads to unexpected or
undesired behaviors (e.g. less precise test coverage).
Compilation cache generated by one version of Node.js can not be reused by a different
version of Node.js. Cache generated by different versions of Node.js will be stored
separately if the same base directory is used to persist the cache, so they can co-exist.
At the moment, when the compile cache is enabled and a module is loaded afresh, the
code cache is generated from the compiled code immediately, but will only be written
to disk when the Node.js instance is about to exit. This is subject to change. The
[`module.flushCompileCache()`][] method can be used to ensure the accumulated code cache
is flushed to disk in case the application wants to spawn other Node.js instances
and let them share the cache long before the parent exits.
### `module.constants.compileCacheStatus`
<!-- YAML
added: v22.8.0
-->
> Stability: 1.1 - Active Development
The following constants are returned as the `status` field in the object returned by
[`module.enableCompileCache()`][] to indicate the result of the attempt to enable the
[module compile cache][].
<table>
<tr>
<th>Constant</th>
<th>Description</th>
</tr>
<tr>
<td><code>ENABLED</code></td>
<td>
Node.js has enabled the compile cache successfully. The directory used to store the
compile cache will be returned in the <code>directory</code> field in the
returned object.
</td>
</tr>
<tr>
<td><code>ALREADY_ENABLED</code></td>
<td>
The compile cache has already been enabled before, either by a previous call to
<code>module.enableCompileCache()</code>, or by the <code>NODE_COMPILE_CACHE=dir</code>
environment variable. The directory used to store the
compile cache will be returned in the <code>directory</code> field in the
returned object.
</td>
</tr>
<tr>
<td><code>FAILED</code></td>
<td>
Node.js fails to enable the compile cache. This can be caused by the lack of
permission to use the specified directory, or various kinds of file system errors.
The detail of the failure will be returned in the <code>message</code> field in the
returned object.
</td>
</tr>
<tr>
<td><code>DISABLED</code></td>
<td>
Node.js cannot enable the compile cache because the environment variable
<code>NODE_DISABLE_COMPILE_CACHE=1</code> has been set.
</td>
</tr>
</table>
### `module.enableCompileCache([cacheDir])`
<!-- YAML
added: v22.8.0
-->
> Stability: 1.1 - Active Development
* `cacheDir` {string|undefined} Optional path to specify the directory where the compile cache
will be stored/retrieved.
* Returns: {Object}
* `status` {integer} One of the [`module.constants.compileCacheStatus`][]
* `message` {string|undefined} If Node.js cannot enable the compile cache, this contains
the error message. Only set if `status` is `module.constants.compileCacheStatus.FAILED`.
* `directory` {string|undefined} If the compile cache is enabled, this contains the directory
where the compile cache is stored. Only set if `status` is
`module.constants.compileCacheStatus.ENABLED` or
`module.constants.compileCacheStatus.ALREADY_ENABLED`.
Enable [module compile cache][] in the current Node.js instance.
If `cacheDir` is not specified, Node.js will either use the directory specified by the
[`NODE_COMPILE_CACHE=dir`][] environment variable if it's set, or use
`path.join(os.tmpdir(), 'node-compile-cache')` otherwise. For general use cases, it's
recommended to call `module.enableCompileCache()` without specifying the `cacheDir`,
so that the directory can be overridden by the `NODE_COMPILE_CACHE` environment
variable when necessary.
Since compile cache is supposed to be a quiet optimization that is not required for the
application to be functional, this method is designed to not throw any exception when the
compile cache cannot be enabled. Instead, it will return an object containing an error
message in the `message` field to aid debugging.
If compile cache is enabled successfully, the `directory` field in the returned object
contains the path to the directory where the compile cache is stored. The `status`
field in the returned object would be one of the `module.constants.compileCacheStatus`
values to indicate the result of the attempt to enable the [module compile cache][].
This method only affects the current Node.js instance. To enable it in child worker threads,
either call this method in child worker threads too, or set the
`process.env.NODE_COMPILE_CACHE` value to compile cache directory so the behavior can
be inherited into the child workers. The directory can be obtained either from the
`directory` field returned by this method, or with [`module.getCompileCacheDir()`][].
### `module.flushCompileCache()`
<!-- YAML
added:
- v23.0.0
- v22.10.0
-->
> Stability: 1.1 - Active Development
Flush the [module compile cache][] accumulated from modules already loaded
in the current Node.js instance to disk. This returns after all the flushing
file system operations come to an end, no matter they succeed or not. If there
are any errors, this will fail silently, since compile cache misses should not
interfere with the actual operation of the application.
### `module.getCompileCacheDir()`
<!-- YAML
added: v22.8.0
-->
> Stability: 1.1 - Active Development
* Returns: {string|undefined} Path to the [module compile cache][] directory if it is enabled,
or `undefined` otherwise.
<i id="module_customization_hooks"></i>
## Customization Hooks
<!-- YAML
added: v8.8.0
changes:
- version: v23.5.0
pr-url: https://github.com/nodejs/node/pull/55698
description: Add support for synchronous and in-thread hooks.
- version:
- v20.6.0
- v18.19.0
pr-url: https://github.com/nodejs/node/pull/48842
description: Added `initialize` hook to replace `globalPreload`.
- version:
- v18.6.0
- v16.17.0
pr-url: https://github.com/nodejs/node/pull/42623
description: Add support for chaining loaders.
- version: v16.12.0
pr-url: https://github.com/nodejs/node/pull/37468
description: Removed `getFormat`, `getSource`, `transformSource`, and
`globalPreload`; added `load` hook and `getGlobalPreload` hook.
-->
<!-- type=misc -->
> Stability: 1.2 - Release candidate (asynchronous version)
> Stability: 1.1 - Active development (synchronous version)
There are two types of module customization hooks that are currently supported:
1. `module.register(specifier[, parentURL][, options])` which takes a module that
exports asynchronous hook functions. The functions are run on a separate loader
thread.
2. `module.registerHooks(options)` which takes synchronous hook functions that are
run directly on the thread where the module is loaded.
<i id="enabling_module_customization_hooks"></i>
### Enabling
Module resolution and loading can be customized by:
1. Registering a file which exports a set of asynchronous hook functions, using the
[`register`][] method from `node:module`,
2. Registering a set of synchronous hook functions using the [`registerHooks`][] method
from `node:module`.
The hooks can be registered before the application code is run by using the
[`--import`][] or [`--require`][] flag:
```bash
node --import ./register-hooks.js ./my-app.js
node --require ./register-hooks.js ./my-app.js
```
```mjs
// register-hooks.js
// This file can only be require()-ed if it doesn't contain top-level await.
// Use module.register() to register asynchronous hooks in a dedicated thread.
import { register } from 'node:module';
register('./hooks.mjs', import.meta.url);
```
```cjs
// register-hooks.js
const { register } = require('node:module');
const { pathToFileURL } = require('node:url');
// Use module.register() to register asynchronous hooks in a dedicated thread.
register('./hooks.mjs', pathToFileURL(__filename));
```
```mjs
// Use module.registerHooks() to register synchronous hooks in the main thread.
import { registerHooks } from 'node:module';
registerHooks({
resolve(specifier, context, nextResolve) { /* implementation */ },
load(url, context, nextLoad) { /* implementation */ },
});
```
```cjs
// Use module.registerHooks() to register synchronous hooks in the main thread.
const { registerHooks } = require('node:module');
registerHooks({
resolve(specifier, context, nextResolve) { /* implementation */ },
load(url, context, nextLoad) { /* implementation */ },
});
```
The file passed to `--import` or `--require` can also be an export from a dependency:
```bash
node --import some-package/register ./my-app.js
node --require some-package/register ./my-app.js
```
Where `some-package` has an [`"exports"`][] field defining the `/register`
export to map to a file that calls `register()`, like the following `register-hooks.js`
example.
Using `--import` or `--require` ensures that the hooks are registered before any
application files are imported, including the entry point of the application and for
any worker threads by default as well.
Alternatively, `register()` and `registerHooks()` can be called from the entry point,
though dynamic `import()` must be used for any ESM code that should be run after the hooks
are registered.
```mjs
import { register } from 'node:module';
register('http-to-https', import.meta.url);
// Because this is a dynamic `import()`, the `http-to-https` hooks will run
// to handle `./my-app.js` and any other files it imports or requires.
await import('./my-app.js');
```
```cjs
const { register } = require('node:module');
const { pathToFileURL } = require('node:url');
register('http-to-https', pathToFileURL(__filename));
// Because this is a dynamic `import()`, the `http-to-https` hooks will run
// to handle `./my-app.js` and any other files it imports or requires.
import('./my-app.js');
```
Customization hooks will run for any modules loaded later than the registration
and the modules they reference via `import` and the built-in `require`.
`require` function created by users using `module.createRequire()` can only be
customized by the synchronous hooks.
In this example, we are registering the `http-to-https` hooks, but they will
only be available for subsequently imported modules β in this case, `my-app.js`
and anything it references via `import` or built-in `require` in CommonJS dependencies.
If the `import('./my-app.js')` had instead been a static `import './my-app.js'`, the
app would have _already_ been loaded **before** the `http-to-https` 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 _within_ `my-app.js`, which will not be evaluated until
`my-app.js` is dynamically imported.
If synchronous hooks are used, both `import`, `require` and user `require` created
using `createRequire()` are supported.
```mjs
import { registerHooks, createRequire } from 'node:module';
registerHooks({ /* implementation of synchronous hooks */ });
const require = createRequire(import.meta.url);
// The synchronous hooks affect import, require() and user require() function
// created through createRequire().
await import('./my-app.js');
require('./my-app-2.js');
```
```cjs
const { register, registerHooks } = require('node:module');
const { pathToFileURL } = require('node:url');
registerHooks({ /* implementation of synchronous hooks */ });
const userRequire = createRequire(__filename);
// The synchronous hooks affect import, require() and user require() function
// created through createRequire().
import('./my-app.js');
require('./my-app-2.js');
userRequire('./my-app-3.js');
```
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 `data:`
URL to `--import`:
```bash
node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register("http-to-https", pathToFileURL("./"));' ./my-app.js
```
### Chaining
It's possible to call `register` more than once:
```mjs
// entrypoint.mjs
import { register } from 'node:module';
register('./foo.mjs', import.meta.url);
register('./bar.mjs', import.meta.url);
await import('./my-app.mjs');
```
```cjs
// entrypoint.cjs
const { register } = require('node:module');
const { pathToFileURL } = require('node:url');
const parentURL = pathToFileURL(__filename);
register('./foo.mjs', parentURL);
register('./bar.mjs', parentURL);
import('./my-app.mjs');
```
In this example, the registered hooks will form chains. These chains run
last-in, first out (LIFO). If both `foo.mjs` and `bar.mjs` define a `resolve`
hook, they will be called like so (note the right-to-left):
node's default β `./foo.mjs` β `./bar.mjs`
(starting with `./bar.mjs`, then `./foo.mjs`, then the Node.js default).
The same applies to all the other hooks.
The registered hooks also affect `register` itself. In this example,
`bar.mjs` will be resolved and loaded via the hooks registered by `foo.mjs`
(because `foo`'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.
The `register` method cannot be called from within the module that defines the
hooks.
Chaining of `registerHooks` work similarly. If synchronous and asynchronous
hooks are mixed, the synchronous hooks are always run first before the asynchronous
hooks start running, that is, in the last synchronous hook being run, its next
hook includes invocation of the asynchronous hooks.
```mjs
// entrypoint.mjs
import { registerHooks } from 'node:module';
const hook1 = { /* implementation of hooks */ };
const hook2 = { /* implementation of hooks */ };
// hook2 run before hook1.
registerHooks(hook1);
registerHooks(hook2);
```
```cjs
// entrypoint.cjs
const { registerHooks } = require('node:module');
const hook1 = { /* implementation of hooks */ };
const hook2 = { /* implementation of hooks */ };
// hook2 run before hook1.
registerHooks(hook1);
registerHooks(hook2);
```
### Communication with module customization hooks
Asynchronous hooks run on a dedicated thread, separate from the main
thread that runs application code. This means mutating global variables won't
affect the other thread(s), and message channels must be used to communicate
between the threads.
The `register` method can be used to pass data to an [`initialize`][] hook. The
data passed to the hook may include transferable objects like ports.
```mjs
import { register } from 'node:module';
import { MessageChannel } from 'node:worker_threads';
// This example demonstrates how a message channel can be used to
// communicate with the hooks, by sending `port2` to the hooks.
const { port1, port2 } = new MessageChannel();
port1.on('message', (msg) => {
console.log(msg);
});
port1.unref();
register('./my-hooks.mjs', {
parentURL: import.meta.url,
data: { number: 1, port: port2 },
transferList: [port2],
});
```
```cjs
const { register } = require('node:module');
const { pathToFileURL } = require('node:url');
const { MessageChannel } = require('node:worker_threads');
// This example showcases how a message channel can be used to
// communicate with the hooks, by sending `port2` to the hooks.
const { port1, port2 } = new MessageChannel();
port1.on('message', (msg) => {
console.log(msg);
});
port1.unref();
register('./my-hooks.mjs', {
parentURL: pathToFileURL(__filename),
data: { number: 1, port: port2 },
transferList: [port2],
});
```
Synchronous module hooks are run on the same thread where the application code is
run. They can directly mutate the globals of the context accessed by the main thread.
### Hooks
#### Asynchronous hooks accepted by `module.register()`
The [`register`][] 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.
```mjs
export async function initialize({ number, port }) {
// Receives data from `register`.
}
export async function resolve(specifier, context, nextResolve) {
// Take an `import` or `require` specifier and resolve it to a URL.
}
export async function load(url, context, nextLoad) {
// Take a resolved URL and return the source code to be evaluated.
}
```
Asynchronous hooks are run in a separate thread, isolated from the main thread where
application code runs. That means it is a different [realm][]. The hooks thread
may be terminated by the main thread at any time, so do not depend on
asynchronous operations (like `console.log`) to complete. They are inherited into
child workers by default.
#### Synchronous hooks accepted by `module.registerHooks()`
<!-- YAML
added: v23.5.0
-->
> Stability: 1.1 - Active development
The `module.registerHooks()` method accepts synchronous hook functions.
`initialize()` is not supported nor necessary, as the hook implementer
can simply run the initialization code directly before the call to
`module.registerHooks()`.
```mjs
function resolve(specifier, context, nextResolve) {
// Take an `import` or `require` specifier and resolve it to a URL.
}
function load(url, context, nextLoad) {
// Take a resolved URL and return the source code to be evaluated.
}
```
Synchronous hooks are run in the same thread and the same [realm][] where the modules
are loaded. Unlike the asynchronous hooks they are not inherited into child worker
threads by default, though if the hooks are registered using a file preloaded by
[`--import`][] or [`--require`][], child worker threads can inherit the preloaded scripts
via `process.execArgv` inheritance. See [the documentation of `Worker`][] for detail.
In synchronous hooks, users can expect `console.log()` to complete in the same way that
they expect `console.log()` in module code to complete.
#### Conventions of hooks
Hooks are part of a [chain][], even if that chain consists of only one
custom (user-provided) hook and the default hook, which is always present. Hook
functions nest: each one must always return a plain object, and chaining happens
as a result of each function calling `next<hookName>()`, which is a reference to
the subsequent loader's hook (in LIFO order).
A hook that returns a value lacking a required property triggers an exception. A
hook that returns without calling `next<hookName>()` _and_ without returning
`shortCircuit: true` also triggers an exception. These errors are to help
prevent unintentional breaks in the chain. Return `shortCircuit: true` from a
hook to signal that the chain is intentionally ending at your hook.
#### `initialize()`
<!-- YAML
added:
- v20.6.0
- v18.19.0
-->
> Stability: 1.2 - Release candidate
* `data` {any} The data from `register(loader, import.meta.url, { data })`.
The `initialize` hook is only accepted by [`register`][]. `registerHooks()` does
not support nor need it since initialization done for synchronous hooks can be run
directly before the call to `registerHooks()`.
The `initialize` 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 [`register`][].
This hook can receive data from a [`register`][] invocation, including
ports and other transferable objects. The return value of `initialize` can be a
{Promise}, in which case it will be awaited before the main application thread
execution resumes.
Module customization code:
```mjs
// path-to-my-hooks.js
export async function initialize({ number, port }) {
port.postMessage(`increment: ${number + 1}`);
}
```
Caller code:
```mjs
import assert from 'node:assert';
import { register } from 'node:module';
import { MessageChannel } from 'node:worker_threads';
// This example showcases how a message channel can be used to communicate
// between the main (application) thread and the hooks running on the hooks
// thread, by sending `port2` to the `initialize` hook.
const { port1, port2 } = new MessageChannel();
port1.on('message', (msg) => {
assert.strictEqual(msg, 'increment: 2');
});
port1.unref();
register('./path-to-my-hooks.js', {
parentURL: import.meta.url,
data: { number: 1, port: port2 },
transferList: [port2],
});
```
```cjs
const assert = require('node:assert');
const { register } = require('node:module');
const { pathToFileURL } = require('node:url');
const { MessageChannel } = require('node:worker_threads');
// This example showcases how a message channel can be used to communicate
// between the main (application) thread and the hooks running on the hooks
// thread, by sending `port2` to the `initialize` hook.
const { port1, port2 } = new MessageChannel();
port1.on('message', (msg) => {
assert.strictEqual(msg, 'increment: 2');
});
port1.unref();