-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathnodejs.javascript.txt
5180 lines (4604 loc) · 386 KB
/
nodejs.javascript.txt
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
┏━━━━━━━━━━━━┓
┃ NODEJS ┃
┗━━━━━━━━━━━━┛
Todo:
- document CRYPTO: Cryto|crypto|CryptoKey|SubtleCrypto global, generateKey[Sync](), CryptoKey, util.types.*key,
getCipherInfo(), hkdf[Sync](), webcrypto, X509Certificate, NodeEdKey*, subtle, fingerprint512, --no-experimental-global-webcrypto
- document http/2
- document quic (including NET.createQuicSocket())
┌──────────────────┐
│ COMMAND LINE │
└──────────────────┘
PURPOSE ==> #Execute JavaScript code server-side
#Based on Chrome JavaScript engine V8
VERSION ==> #23.10.0 (current), 22.14.0 (active LTS), 20.19.0 (maintenance LTS), 18.20.7 (maintenance LTS)
#Branches:
# - "current": latest major version. New one every 0.5 years
# - LTS: every even-numbered version
# - when not current anymore, becomes "active LTS" (only bug fixes) for 1.5 years
# - then "maintainance LTS" (only critical bug fixes) for 1 more year
# - non-LTS also have a maintainance period of 0.5 years
#Features are often backported.
NUM*#Means introduced by NUM.*.*
ES6 ==> #Support is documented in JavaScript doc
node[js] [--] [FILE] [FILE_ARGS] #Command-line
--entry-url 22.10.0*#Parse FILE as a URI instead, one of:
22.10.0*# - relative URI, e.g. 'FILENAME'
22.10.0*# - 'file:///...'
22.10.0*# - 'data:text/javascript,JAVASCRIPT'
node[js] -e|--eval|-p|--print STR [--] [ARGS] #nodejs is symlink to node (prefer the later as this is what nvm uses).
#FILE is JavaScript file (def: stdin). Can be - too
#With -e, evaluates STR
#With -p, evaluates STR, and prints last return value.
# - cannot be used with --input-type=module
#All CLI flags can use underscores instead of dashes
--run TASK [[--] ARGS] 22.0.0*#Run PACKAGE.scripts.TASK [ARGS]
22.0.0*#Looks into ./node_modules/.bin/
22.3.0*#Also looks into .../node_modules/.bin/, and updates ENVVAR PATH
22.0.0*#If TASK is missing, list available ones
22.0.0*#Run within a shell (sh on Unix, cmd.exe on Windows). Single-quote ARGS
ENVVAR NODE_RUN_SCRIPT_NAME 22.3.0*#'TASK', during --run
ENVVAR NODE_RUN_PACKAGE_JSON_PATH 22.3.0*#'PATH' to package.json, during --run
-i
--interactive #Enters REPL even if stdin does not come from a terminal
-c
--check #Run-dry (syntax check)
--watch #Restart process on file changes (including imported files)
--watch-path #Changes which files are watched. Only Windows|macOS
--watch-preserve-output 18.13.0*#Do not clear screen when --watch restarts process
--completion-bash #Output Bash completion script (for CLI flags)
#!/usr/bin/env node #Shabang to execute a Node file directly with ./FILE
npm #Node packet manager (see doc)
corepack #Packet manager's manager
┌────────────┐
│ CONFIG │
└────────────┘
NODE_OPTIONS=--OPT,... ENVVAR #Same as using node --OPT ...
--v8-options #Prints available v8 options.
process.allowedNodeEnvironmentFlags #Read-only SET with all available NODE_OPTIONS
--experimental-config-file=PATH.json 23.10.0*#PATH to CONF
CONF.schema 23.10.0*#Must be set to 'https://nodejs.org/dist/vX.Y.Z/docs/node-config-schema.json'
CONF.nodeOptions.OPT 23.10.0*#VAL. Sets CLI flag
--experimental-default-config-file 23.10.0*#Look for ./node.config.json
┌────────────┐
│ TIMERS │
└────────────┘
clear|setTimeout|Interval(...) #Like DOM ones (see DOM doc), but extra members
clear|setImmediate(...) #Unlike DOM, error if INT > 2 ** 31 - 1 (25 days)
#ID is not returned when using util.promisify()
ID.[un]ref()->ID #Yield the macrotask (see JavaScript doc)
ID.hasRef()->BOOL #
ID.refresh()->ID #Reset the counter
ID[Symbol.toPrimitive]()->ID_NUM #
ID_NUM #Can be passed to clear*(...)
ID[Symbol.dispose]() 18.18.0*#Calls clear*(...)
queueMicrotask(FUNC()) #Add a new microtask (see DOM|JavaScript doc)
process.nextTick(FUNC()[, ...]) #Add a new microtask (see JavaScript doc)
#As opposed to queueMicrotask(), always processed before other microtasks,
#including when calling itself recursively.
#Prefer queueMicrotask()
require('timers/promises') #
TIMERS.promises 20.12.0*#
setTimeout(NUM[, VAL[, OPTS]])->> #Resolves to VAL (def: undefined) after NUMms.
setImmediate([VAL[, OPTS]])->> #OPTS:
# - ref BOOL (def: true): yield macrotask
# - signal ABORT_SIGNAL: call clear* on cancel, and throws
#Those OPTS are available to promisify(setTimeout|setImmediate) too
setInterval(NUM[, VAL[, OPTS]]) #Same but for setInterval()
->ASYNC_ITERATOR #ASYNC_ITERATOR is resolving to VAL each time
scheduler.wait(NUM[, OPTS])->> #Like DOM. No OPTS.ref
scheduler.yield()->PROMISE #Like DOM.
┌─────────────────┐
│ ASYNC HOOKS │
└─────────────────┘
TASK_ID #Microtask ID
#Is incrementing counter, with top-level microtask having ID 1
#Specifics:
# - ID 0 means executed from C++, not JavaScript
# - PROMISE report parent microtask's, not their actual microtask ID, unless
# an enabled HOOK exists
# - async|await (but PROMISE) report parent microtask's, not their actual microtask ID
RESOURCE #Any resource, firing 0, 1 or several microtasks (depends on RESOURCE_TYPE)
#RESOURCE properties depend on RESOURCE_TYPE. They might not be populated yet in init()
RESOURCE_TYPE #Can be:
# - TickObject: process.nextTick()
# - properties: callback FUNC, [args 'VAL'_ARR]
# - Immediate: setImmediate()
# - properties: _onImmediate FUNC, [_argv 'VAL'_ARR]
# - Timeout: setTimeout|setInterval()
# - properties:
# - _onTimeout FUNC
# - _idleTimeout NUM
# - _repeat null|NUM: same but null with setTimeout()
# - [_timerArgs 'VAL'_ARR]
# - TIMERWRAP: setTimeout|setInterval()
# - PROMISE:
# - on:
# - new Promise(FUNC), Promise.resolve|reject()
# - PROMISE.then|catch|finally(FUNC), await PROMISE
# - calling an async FUNC
# - TTYWRAP: console.*
# - properties: callback FUNC, [args 'VAL'_ARR]
# - SIGNALWRAP: OS signal
# - FSEVENTWRAP, FSREQWRAP, GETADDRINFOREQWRAP, GETNAMEINFOREQWRAP, HTTPPARSER,
# JSSTREAM, PIPECONNECTWRAP, PIPEWRAP, PROCESSWRAP, QUERYWRAP, SHUTDOWNWRAP,
# STATWATCHER, TCPCONNECTWRAP, TCPSERVER, TCPWRAP, UDPSENDWRAP, UDPWRAP,
# WRITEWRAP, ZLIB, SSLCONNECTION, PBKDF2REQUEST, RANDOMBYTESREQUEST, TLSWRAP: others
executionAsyncId()->TASK_ID #Current microtask
triggerAsyncId()->PARENT_TASK_ID #Parent microtask, i.e. caller
executionAsyncResource()->RESOURCE #Current microtask's RESOURCE
process.getActiveResourcesInfo()
->RESOURCE_TYPE_ARR #Return all current RESOURCEs
createHook(OPTS)->HOOK #Fires callbacks on new microtasks|resources, using OPTS:
# - init(TASK_ID, RESOURCE_TYPE, PARENT_TASK_ID, RESOURCE):
# - when RESOURCE is initialized.
# - before|after(TASK_ID):
# - before|after each microtask starts|ends
# - since some RESOURCE create no microtasks, or several,
# this might not be called, or be called several times
# - destroy(TASK_ID): when RESOURCE is destroyed
# - promiseResolve(TASK_ID):
# - when a PROMISE is resolved|rejected, including to another PROMISE2
# - only for RESOURCE_TYPE PROMISE
#Exceptions thrown in callbacks are uncaught exceptions, but cannot be handled.
#Doing async operations (i.e. creating microtasks) inside callbacks:
# - can cause infinite recursion
# - this includes console.*(), which can be replaced e.g. by
# fs.writeSync(1, util.format(VAL))
HOOK.enable|disable()->HOOK #HOOK callbacks will only be fired in enabled (disabled by def)
new AsyncResource('RESOURCE_TYPE'[, OPTS]) #Custom RESOURCE
#OPTS:
# - triggerAsyncId PARENT_TASK_ID (def: executionAsyncId())
# - requireManualDestroy BOOL: if false (def), calls emitDestroy() when object
# is garbage collected
ASYNCRESOURCE.runInAsyncScope
(FUNC[, THIS][, ...ARGS]) #This is automatically create a new TASK_ID and call 'before|after' events
ASYNCRESOURCE.bind(FUNC[, THIS])->FUNC2 #Like ASYNCRESOURCE.runInAsyncScope.bind(FUNC)
AsyncResource.bind
(FUNC[, 'RESOURCE_TYPE'][, THIS]) #Like (new AsyncResource('RESOURCE_TYPE')).bind(FUNC)
->FUNC2 #Def 'RESOURCE_TYPE': 'bound-anonymous-fn'
ASYNCRESOURCE.emitDestroy() #
ASYNCRESOURCE.asyncId()->TASK_ID #
ASYNCRESOURCE.triggerId()->PARENT_TASK_ID #
new EventEmitterAsyncResource(OPTS) #EVENTEMITTER wrapper around ASYNC_RESOURCE
#OPTS:
# - name 'RESOURCE_TYPE', triggerAsyncId, requireManualDestroy: passed to new AsyncResource()
# - captureRejections BOOL: passed to new EventEmitter()
EVENTEMITTER_ASYNC_RESOURCE
.asyncResource #ASYNC_RESOURCE
EVENTEMITTER_ASYNC_RESOURCE
.emitDestroy|asyncId|triggerAsyncId #Same as ASYNC_RESOURCE.*
--no-force-async-hooks-checks #Do not do extra runtime checks related to async hooks
new AsyncLocalStorage([OPTS]) #Create STOREs, i.e. objects available inside a specific function and its closures (including async)
ASYNC_LOCAL_STORAGE.run(STORE, FUNC()) #Creates a STORE that only exists within the current async context.
#An async context is the current function and its closures including async ones (promise or callback).
#Creates a new async context
#STORE is undefined outside that context.
#STORE is cleaned up once the context stops.
#STORE can be anything (e.g. an OBJ or MAP)
ASYNC_LOCAL_STORAGE.getStore()->STORE #Retrieve the STORE
ASYNC_LOCAL_STORAGE.disable() #Make all STORE undefined until run*() called again
#Should be called to cleanup ASYNC_LOCAL_STORAGE itself (not its STOREs)
ASYNC_LOCAL_STORAGE.enterWithStore(STORE) #Make getStore() return STORE for the current synchronous context (current function and its sync closures)
ASYNC_LOCAL_STORAGE.exit #Opposite
(FUNC([...ARGS])[, ...ARGS]) #Creates a new async context
ASYNC_LOCAL_STORAGE.bind(FUNC)->FUNC 18.16.0*#Similar to ASYNCRESOURCE.bind()
ASYNC_LOCAL_STORAGE.snapshot()->FUNC 18.16.0*#Same as ASYNC_LOCAL_STORAGE.bind((FUNC, ...ARGS) => FUNC(...ARGS))
asyncWrapProviders #OBJ with all possible RESOUCE_TYPE and associated number ids
--experimental-async-context-frame 22.7.0*#Uses a different implementation for AsyncLocalStorage that is based on some new V8 API
22.7.0*#instead of using HOOKs
┌──────────────────┐
│ PROMISEHOOKS │
└──────────────────┘
V8.promiseHooks #Module of the following methods
#Event handlers fired on any PROMISEs.
#Used under the hood by ASYNC_HOOKS, but without RESOURCEs
onEVENT(FUNC(...))->FUNC2() #Add an event handler.
#FUNC2 removes it.
#FUNC must not using PROMISEs to avoid infinite loops.
#Available EVENTs:
# - init(PROMISE, PARENT_PROMISE): PROMISE creation
# - before|after(PROMISE):
# - before|after a child PROMISE starts|ends
# - may be called 0-n times
# - settled(PROMISE): PROMISE resolution|rejection
createHook(OBJ)->FUNC2() #Same using OBJ.EVENT(...) instead
┌──────────────┐
│ DEBUGGER │
└──────────────┘
--inspect[-wait|-brk][=[HOST:]PORT] ... #Launches node ... but with debugger server.
#Must connect to it with a debugger client:
# - go to chrome://inspect and click on a link to open devtools
# - or directly click on the Node symbol in devtools
#Also forwards console messages
#Beginning behavior:
# - no -wait|-brk: breakpoints ignored until a client is connected
20.15.0*# - -wait: wait for client to be connected before running code
# - -brk: run code but breakpoint at first line of user code
#HOST: def 127.0.0.1
#PORT: def 9229, 0 for "any available"
#Child processes must be started with node --inspect as well
--inspect-publish-uid=STR,... #How the debugging information is communicated among:
# - 'http' (def): endpoint at HOST:PORT/json/list
# - 'stderr' (def)
IRON-NODE ==> ##Another way to debug is to use Electron.
JAM3 DEVTOOL ==> ##Those two apps do this
##There are many problems I encountered with those, so I prefer node --inspect
--node-memory-debug #Add some low-level memory debug messages
┌───────────┐
│ ERROR │
└───────────┘
ERROR #Are v8 errors, i.e. what follows is shared by Chrome
#See JavaScript doc for more information, including on async stack trace
ERROR.stack #Start with the innermost source line, before ERROR.name|message if either:
# - source maps are applied
# - uncaught exception
--stack-trace-limit=NUM #Sets Error.stackTraceLimit
NERROR #Node internal error, as opposed to standard JavaScript ERROR
#Often filesystem errors, including permissions
NERROR.code #NERROR_NAME
#Either:
# - E*: cross-OS
# - W*: Windows-specific
# - ERR_*: otherwise
#E*|W*:
# - only if SYSTEMERROR
# - have an underlying NERROR_NUM (OS-specific number)
SYSTEMERROR #NERROR related to OS/environment issue.
#Not its own error type: it is an Error instance.
SYSTEMERROR.errno #-NERROR_NUM
UTIL.getSystemErrorName(-NERROR_NUM)->NEROR_NAME#
OS.constants.errno.NERROR_NAME #NERROR_NUM
UTIL.getSystemErrorMap()->MAP #Key is -NERROR_NUM, value is ARR of ['NERROR_NAME', 'DESCRIPTION']
UTIL.getSystemErrorMessage(-NERROR_NUM)
->'DESCRIPTION' 23.1.0*#
SYSTEMERROR.syscall #STR (e.g. 'access')
SYSTEMERROR.path|dest #Src|dest 'PATH', if any
SYSTEMERROR.address|port #HOST|PORT, if any
SYSTEMERROR.info #Extra info, if any
--no-extra-info-on-fatal-exception #Do not print Node.js versions on process errors (e.g. top-level uncaught
#exceptions, unhandled promises, etc.)
┌────────────┐
│ EVENTS │
└────────────┘
new EventEmitter([OPTS]) #Base class of all objects receiving events
#'EVENT' can be a SYM
#Events are emitted synchronously
EVENTEMITTER.on|addListener
('EVENT', FUNC)->EVENTEMITTER #
EVENTEMITTER.once('EVENT', FUNC)->EVENTEMITTER #
EVENTEMITTER.prepend[Once]Listener(...) #Like on[ce](...) but adds to beginning of listeners list, not end
once(EVENTEMITTER|EVENTTARGET, 'EVENT'[, OPTS]) #Like EVENTEMITTER.once() but using PROMISE:
->PROMISE_ARG_ARR # - resolved with ARG_ARR on emit('EVENT', ...ARGS)
# - rejected with VAL on emit('error', VAL) (unless 'EVENT' is 'error' itself)
#OPTS:
# - signal ABORT_SIGNAL
on(EVENTEMITTER|EVENTTARGET, 'EVENT'[,OPTS]) #Same but for EVENTEMITTER.on(), as a an ASYNC_ITERATOR
->ASYNC_ITERATOR #OPTS:
# - signal ABORT_SIGNAL: on abort, throws AbortError
# - close 'EVENT'_ARR (def: []): stop on those events
# - highWaterMark|lowWaterMark NUM (def: Infinity|1):
# - only when EVENTEMITTER has .pause|resume() (e.g. STREAM)
# - pause STREAM on NUM of buffered events > highWatermark, resume on < lowWaterMark
# - NUM is number of events, not byte size
<20.13.0*# - previously called highWatermark|lowWatermark
#Buffers events infinitely
# - on throw|return, discard them
EVENTEMITTER.off|removeListener('EVENT', FUNC)
->EVENTEMITTER #
EVENTEMITTER.removeAllListeners(['EVENT'])
->EVENTEMITTER #
EVENTEMITTER.emit('EVENT'[, ...])->BOOL #True if there were listeners
#If 'EVENT' is 'error' and there are no listeners, throws instead
EVENTEMITTER.listeners('EVENT')->FUNC_ARR
getEventListeners
(EVENTEMITTER|EVENT_TARGET, 'EVENT')->FUNC_ARR #
EVENTEMITTER.rawListeners('EVENT')->FUNC_ARR #Same but also with what Node.js adds, e.g. once() wrapper
EVENTEMITTER.listenerCount #Slightly faster than EVENTEMITTER.listeners(STR).length
('EVENT'[, FUNC])->NUM 18.16.0*#Can filter for a specific listener FUNC only
EVENTEMITTER.eventNames()->'EVENT'_ARR #
EVENTEMITTER.setMaxListeners(NUM)->EVENTEMITTER
setMaxListeners
(NUM, EVENT_EMITTER|EVENT_TARGET...) #0 for unlim. Beyond max, does not stops adding listeners, only print warning.
EVENTEMITTER.getMaxListeners()->NUM #
getMaxListeners(EVENT_EMITTER|EVENT_TARGET...)
->NUM 18.17.0*#Same
EVENTEMITTER.defaultMaxListeners #10
EVENTEMITTER.on #Event when a new event handler is added or removed.
("new|removeListener", FUNC(EVENT, FUNC2)) #Added|removed FUNC2 might still [not] be in EVENTEMITTER.listeners(EVENT)
OPTS.captureRejections #BOOL. Enables Symbol.for('nodejs.rejection')
EventEmitter.captureRejections #Default value for OPTS.captureRejections (def: false)
EVENTEMITTER[Symbol.for('nodejs.rejection')] #Can be set to a FUNC(VAL, 'EVENT', ...ARGS)
EVENTEMITTER[captureRejectionSymbol] #Fired when an EVENTEMITTER handler returns a PROMISE rejected with VAL.
#If not set, fire 'error' event handler FUNC(VAL) instead.
#Not recursive (not done if 'nodejs.rejection' or 'error' event handler rejects a PROMISE themselves).
EventEmitter.errorMonitor #Special 'EVENT' that behaves like 'error' except if no 'error' listener is
#defined, an error is still thrown afterwards
EventTarget #Like DOM except:
# - can be async
# - no event nesting
#Notable differences between DOM EventTarget and Node.js EventEmitter:
# - listeners are EVENTLISTENER: either FUNC or { handleEvent(EVENT) }
# - cannot add same listener several times to same OBJ
#Exposed globally
NodeEventTarget #Child of EventTarget that mixes most Node.js EventEmitter properties|methods:
# - only on|once|off|addListener|removeListener|removeAllListeners|emit
# listenerCount|eventNames|*etMaxListeners|defaultMaxListeners
#Not exposed globally
Event #Like DOM, including:
19.5.0*# - EVENT.initEvent()
#Exposed globally
CustomEvent #Like DOM
--experimental-global-customevent <19.0.0*#Required to expose CustomEvent globally
┌───────────┐
│ ABORT │
└───────────┘
new AbortController() #Like DOM
new AbortSignal() #Like DOM. Child of EventTarget
#Most OPTS.signal used in this doc throw|reject with AbortError
#Including:
# - AbortSignal.abort()
# - ABORT_SIGNAL.reason
# - AbortSignal.timeout(), ABORT_SIGNAL.throwIfAborted()
18.17.0*# - AbortSignal.any()
util.transferableAbortController()
->ABORT_CONTROLLER 18.11.0*#Same as new AbortController() but can be used with postMessage|structuredClone() (not IPC sendMessage())
util.transferableAbortSignal
(ABORT_SIGNAL)->ABORT_SIGNAL2 18.11.0*#Same but for AbortSignal
util.aborted(ABORT_SIGNAL, OBJ)->> 18.16.0*#Waits until aborted
18.16.0*#OBJ must not be garbage collectable, otherwise promise will hang
events.addAbortListener 18.18.0*#Like ABORT_SIGNAL.addEventListener('abort', EVENTLISTENER) except works even if:
(ABORT_SIGNAL, EVENTLISTENER)->OBJ 18.18.0*# - another listener calls EVENT.stopImmediatePropagation()
18.18.0*# - ABORT_SIGNAL already aborted
18.18.0*#Returns OBJ, with OBJ[Symbol.dispose]() calling removeEventListener('abort')
┌─────────────────────────┐
│ DIAGNOSTICS_CHANNEL │
└─────────────────────────┘
CHANNEL_NAME #STR|SYM
#Should be namespaced since this is global
channel('CHANNEL_NAME')->CHANNEL #Global EVENT_EMITTER-like meant for debugging information
CHANNEL.publish(MESSAGE) #MESSAGE can be any VAL
CHANNEL.hasSubscribers #BOOL
subscribe('CHANNEL_NAME',
FUNC(MESSAGE, 'CHANNEL_NAME')) #
unsubscribe('CHANNEL_NAME', FUNC)->BOOL #BOOL is whether FUNC was subscribed to
hasSubscribers('CHANNEL_NAME')->BOOL #
CHANNEL.runStores
(MESSAGE, FUNC(...ARGS)->VAL
[, CONTEXT[, ...ARGS]])->VAL 18.19.0*#Call CHANNEL.publish(MESSAGE), then run FUNC() with MESSAGE set as STORE
CHANNEL.bindStore(ASYNC_LOCAL_STORAGE 18.19.0*#Associate a CHANNEL with an ASYNC_LOCAL_STORAGE inside runStores() FUNC
[, FUNC(STORE)->STORE]) 18.19.0*#FUNC transforms STORE on runStores()
CHANNEL.unbindStore(ASYNC_LOCAL_STORAGE)18.1
->BOOL 18.19.0*#Returns false if not present
TRACING_CHANNEL 18.19.0*#Collection of 5 CHANNELs gathering different MOMENTs of each event
18.19.0*#MOMENT is [async]start|end or 'error'
tracing:TRACING_CHANNEL_NAME:MOMENT 18.19.0*#CHANNEL_NAME of a TRACING_CHANNEL
TRACING_CHANNEL_MESSAGE.result 18.19.0*#Set on MOMENT [async]end
TRACING_CHANNEL_MESSAGE.error 18.19.0*#Set on MOMENT [async]end|error
tracingChannel('TRACING_CHANNEL_NAME'|
{ MOMENT: CHANNEL, ... })
->TRACING_CHANNEL 18.19.0*#
TRACING_CHANNEL.subscribe
({ MOMENT(MESSAGE), ... }) 18.19.0*#
TRACING_CHANNEL.unsubscribe
({ MOMENT(MESSAGE), ... })->BOOL 18.19.0*#
TRACING_CHANNEL.traceSync(...) 18.19.0*#Like CHANNEL.runStores() but publishes start and (if no exception) end or (if exception) error MOMENTs
TRACING_CHANNEL.tracePromise(...) 18.19.0*#Same but with an async FUNC and asyncStart|End and error MOMENTs
TRACING_CHANNEL.traceCallback(...) 18.19.0*#Same but with a callback FUNC
┌──────────────────┐
│ TRACE_EVENTS │
└──────────────────┘
createTracing([OPTS])->TRACING
--trace-events-enabled #Output tracing to a TRACE_FILE
TRACING|OPTS.categories #'CATEGORY'_ARR
--trace-event-categories=CATEGORY,... #Pick tracing CATEGORYs
#Def: v8,node,node.async_hooks
#Also calls --trace-events-enabled
TRACING.getEnabledCategories()->'CATEGORY,...' #
TRACING.enable|disable() #Whether to show trace events
#Those are shown in chrome://tracing
TRACING.enabled #BOOL
--trace-event-file-pattern=PATH #Output trace events to PATH
#Can include ${rotation} and ${pid}
#Def: 'node_trace.${rotation}.log'
AVAILABLE CATEGORIES ==> #
v8 #V8 GC, compiling and execution
node #
node.bootstrap #Node startup
node.environment #Node environment setup
node.realm #Node global object
node.console #console
node.perf #Performance.*
node.perf.usertiming #Performance 'mark|measure'resource'
node.perf.timerify #Performance.timerify()
node.promises.rejections #PROMISEs unhandled or handled too late
node.async_hooks #ASYNC_HOOKS (PROMISE, etc.)
node.threadpoolwork.[a]sync #Blob|ZLIB|CRYPTO|node_api
node.fs.[a]sync #FS except 'DIR'
node.fs_dir.[a]sync #FS for 'DIR'
node.net.native #TCP
node.http #HTTP
node.dns.native #DNS
node.vm.script #VM
TRACE_FILE #v8 tracing file
#Can be visualized with chrome://tracing or ui.perfetto.dev
TRACE_FILE.traceEvents #TRACE_EVENT_ARR
TRACE_EVENT.ph #Event type among:
# - duration: 'B' (begin), 'E' (end)
# - complete: 'X'
# - instant: 'i'
# - counter: 'C'
# - async: 'b' (start), 'e' (end), 'n' (instant)
# - flow: 's' (start), 'f' (end), 't' (step)
# - sample: 'P'
# - object: 'N' (create), 'D' (delete), 'O' (snapshot)
# - metadata: 'M'
# - memory dump: 'V' (global), 'v' (process)
# - mark: 'R'
# - clock sync: 'c'
# - context: ','
TRACE_EVENT.name #Event name
TRACE_EVENT.cat #'CATEGORY,...' tagging an event
TRACE_EVENT.dur #NUMms duration
TRACE_EVENT.tdur #NUMms duration, including thread open|end
TRACE_EVENT.ts #DATE_NUM. Start time, global
TRACE_EVENT.tts #DATE_NUM. Start time, within the thread
TRACE_EVENT.pid #Process ID
TRACE_EVENT.tid #Thread ID
TRACE_EVENT.id #Event-type specific ID
TRACE_EVENT.args #Event-type specific arguments
┌────────────┐
│ GLOBAL │
└────────────┘
GLOBAL VARIABLES ==> # - global|globalThis: global scope reference
# - clear|setImmediate|Interval|Timeout, Object, URL, console, encodeURI, WebAssembly, etc.: JavaScript globals
# - module, require, exports, __filename, __dirname: CommonJS globals
# - process, url: core modules
# - Buffer: core modules property
# - _, _error: REPL only
# - all core modules (e.g. http): in CLI only
--frozen-intrisics #Call Object.freeze() deeply on all global objects.
require('timers') #Module for clear|setImmediate|Interval|Timeout
#Prefer globals as they work on browsers too
--disable-proto=STR #Disallow OBJ.__proto__ (often used for security vulnerabilities)
#STR is 'throw' (throw on access) or 'delete' (remove it)
--disallow-code-generation-from-strings #Disallow eval() and new Function() (but not VM)
┌───────────┐
│ SCOPE │
└───────────┘
SCOPE ==> #Variables are local to each file, except for MODULE.exports|require() or export|import
TOP-LEVEL ==> #CommonJS, import(): any level
#import: must be top-level
TOP-LEVEL CONTEXT ==> #CommonJS: exports, require, module, __filename, __dirname
#ESM: only import, export, import.meta
TOP-LEVEL THIS ==> #CommonJS: module.exports
#ESM: undefined
┌─────────────┐
│ MODULES │
└─────────────┘
STEPS ==> # - resolve relative PATH to absolute PATH
# - fetch|read file
# - sets top-level context
# - parsing
# - running|evaluating
# - cache return value
PARSE-TIME VS RUNTIME ==> #CommonJS, import(): everything done runtime
#import: everything done parse-time:
# - cannot do e.g. export { VAL as [DYNAMIC_VAR] }
# - cannot catch errors in try/catch (e.g. optional dependency)
# - better static analysis
# - VAR are implicitely const
# - also find imported|exported symbols (VAR) and link them
SYNC VS ASYNC ==> #CommonJS: sync
#import:
# - async parsing (parse-time)
# - sync loading (runtime)
#import(): async with PROMISE
CIRCULAR DEPENDENCIES ==> #import(), dynamic require(): no issues
#top-level require():
# - retrieve `module.exports` (not individual properties) by reference (not value)
# - if accessed during file load, empty object (parent not done loading)
# - including destructuring during `require()`
# - but works after file load:
# - unless parent does `module.exports = VAL` (as opposed to `module.exports.VAR = VAL`), as it removes the reference
#import:
# - retrieve individual properties by reference (not value)
# - if accessed synchronously, throws error (parent not done loading)
# - otherwise works
DEFAULT EXPORT ==> #CommonJS: it is the whole export (module.exports)
#ESM: it is a property named 'default'
FORMAT ==> #Decided by:
# - FILE.mjs|cjs -> ESM|CommonJS
# - FILE[.js] -> PACKAGE.type 'module|commonjs' (def: 'commonjs')
# - `package.json` can be in nested directories
# - stdin|--eval|--print -> --input-type module|commonjs
23.6.0*# or module|commonjs-typescript
18.19.0*# - FILE uses export, static (not dynamic) import, or import.meta -> ESM
18.19.0*# - slight performance cost at parsing time
<20.19.0*# - requires --experimental-detect-module
# - else -> commonjs
MIXING ==> #ESM can import CommonJS:
# - module.exports VAL|OBJ is imported as default import
# - module.exports.VAR can also be imported as named import
# - does not work if module.exports.VAR is dynamically set
#CommonJS cannot import ESM:
# - including if ESM is a package (node_modules)
# - but can use dynamic import(), which allows importing ESM
require('module') #Returns CommonJS require().
.createRequire('/PATH'|'URL'|URL) #'PATH|URL' is the relative base (relative itself to __dirname)
->require(STR) # - Must end with '/' if directory
#Can be used to use CommonJS or load PATH.json|node in ESM
#Usually createRequire(import.meta.url)
--experimental-require-module 20.17.0*#Allow calling require() to import ESM
20.17.0*#The return value is the same as a dynamic import(), e.g. default exports are a `default` property
20.17.0*#It also has {__esModule: true} if there is a `default` export
22.12.0*#However, if ESM file does a single named export called 'module.exports', it is used as is by require()
20.17.0*#Fails if either the current file or the imported one has a top-level await
<20.19.0*#Flag not needed anymore
--experimental-print-required-tla 22.0.0*#When calling require() to import ESM and there is a top-level await, print its location
process.features.require_module 20.19.0*#BOOL. True when current file is ESM loaded by require()
--trace-require-module=STR 20.19.0*#Prints any require(ESM) if 'all'
20.19.0*#If 'no-node-modules', do not print when requiring Node modules
DUAL PACKAGES ==> #Alternatives when supporting both old and new Node.js:
# - use different PACKAGE.exports.PATH for CommonJS and ESM
# - use different PACKAGE.exports.CONDITION for CommonJS and ESM
#ESM can be either:
# - ESM source
# - this could be an issue as user could load twice (once with require(), once with import)
# - not an issue if no logic triggered on load nor top-level state
# - ESM small file that loads transpiled ESM source
# - so that exports are known parse-time and named imports can be used
--force-context-aware #Forbids native modules that do side effects during initialization
┌────────────────┐
│ FILE TYPES │
└────────────────┘
require|import ... 'PATH[.js]' #
require|import ... 'PATH.json'
with { type: 'json' } 18.20.5*#
require('PATH.node') #Machine code file.
#Loaded by dlopen()
#exports available in void init(Handle<Object> exports)
#Must use libraries: V8, libuv, others
#Use node-gyp for packaging/compilation
#On Windows, must first npm install -g windows-build-tools as admin
--no-addons #Disable PATH.node
--experimental-addon-modules 23.6.0*#Required with ESM
<23.6.0*#Previously, not possible with ESM
import ... from 'URI.wasm' #Only with ESM
--experimental-wasm-modules #Required for WebAssembly imports
--disable-wasm-trap-handler 20.15.0*#Implement bound checks using sync checks instead of OS signals
20.15.0*#Much slower but does not require 10GB memory
import 'data:MIME,...' #For MIMEs text/javascript, application/json, application/wasm
#Cannot do a nested import inside ...
#Only with ESM
import 'node:ID' #Same as import 'ID' (core module), but valid URI
#Available with require() too
┌──────────────┐
│ COMMONJS │
└──────────────┘
require(STR) #Load file STR:
# - 'ID': core module
# - 'FILE' (absolute or relative)
# - 'DIR' (absolute or relative):
# - DIR/package.json, using main 'PATH' (relative to DIR)
# - DIR/index[.EXT]
# - prints a warning for PACKAGE.main|exports file
# - 'MODULE[/PATH]':
# - i.e. anything that does not start with / or .
# - tries require('DIR2/MODULE'), with DIR2 [.../[..]]./node_modules/
#Paths can omit extensions: .js, .mjs, .cjs, .json, .node
# - decide file type based on file extension
# - prints a warning for PACKAGE.main|exports file
#If not found, throw ERROR with:
# - code "MODULE_NOT_FOUND"
# - requireStack 'PATH'_ARR
MODULE.require(...) #Reference to require(...)
-r|--require STR #Calls require() (CommonJS)
--import=PATH 18.18.0*#Calls import() (ESM)
require.resolve(STR[, OPTS])->'/PATH' #How require(STR) would resolve, based on __filename.
#OPTS:
# - paths 'DIR'_ARR: alternative directories to look into.
# Their [.../[..]]./node_modules will always be searched.
require.resolve.paths(STR)->'DIR'_ARR #Directories that would be looked into when require(STR) would resolve
import.meta.resolve(STR[, CURRENT_URL]) #Same as require.resolve() but for ESM
->'file://...' #CURRENT_URL is STR|URL
#Returns 'node:*' for core modules
#ERROR with code 'ERR_MODULE_NOT_FOUND' if cannot find
<18.19.0*#Used to return a PROMISE
--experimental-import-meta-resolve #Needed to use CURRENT_URL with import.meta.resolve()
<18.19.0*#Needed to use import.meta.resolve()
findPackageJSON 22.14.0*#Find closest package.json starting from DIR or FILE's DIR
('MODULE|'FILE'|'DIR'|URL 22.14.0*#PATH2|URL2 is relative base of PATH|URL (optional if first argument is absolute)
[, 'PATH2'|URL2])[->'PATH3'] 22.14.0*#Returns undefined if not found
22.14.0*#If 'MODULE', same as import.meta.resolve() instead
require.cache['/PATH'] #require() cache (i.e. modules are only loaded once).
#'/PATH' is require.resolve() result
#Does not include builtins.
#Can delete it to remove cache, or restart current code.
--preserve-symlinks #When require()|import a symlink, use symlink path instead of symlinked file's path for:
# - caching
# - module resolution (when walking up the tree)
#Does not apply to main file
--preserve-symlinks-main #Same but only for main file
exports #Return value (by reference if OBJ) when required. Must be assigned sync.
#Can be any type.
MODULE.exports #Reference to exports.
#Must be used when want to overwrite, i.e. exports = VAL (as opposed to exports.VAR = VAL)
module #Current MODULE, i.e. file being loaded.
#There are builtin modules, which are the chapters of this doc.
require.main #Root file (first to have been loaded) MODULE
process.mainModule #Same but updated if root file changed at runtime
MODULE.children #MODULE[_ARR]|null
MODULE.isPreloading #BOOL. True when inside node -r
MODULE.loaded #False for the first time the file is loaded (i.e. sync)
#True for async functions
require('module').builtinModules #List of system 'MODULE'_ARR (e.g. 'http') including internal ones
require('repl').builtinModules #Same
require('module').isBuiltin(STR)->BOOL #true if 'node:ID' core module
process.getBuiltinModule
(STR)->OBJ|undefined 20.16.0*#Like import('node:ID') but sync
__filename #Current file absolute path.
MODULE.filename #Reference to __filename
MODULE.id #For core modules, a string like "buffer". For others, module.filename.
__dirname #Current file absolute dirname
CLI ==> #Not defined: require.main, process.mainModule, __filename, __dirname
#MODULE.loaded: false
#MODULE.id: '<repl>'
#MODULE.exports: empty OBJ
#MODULE.filename null
--no-global-search-paths #Disable deprecated ENVVAR NODE_PATH and ~/.node_modules
DIAGNOSTICS_CHANNEL.subscribe
('module.require.start|end', FUNC(OBJ)) 22.4.0*#OBJ: id 'MODULE', parentFilename 'PATH'
DIAGNOSTICS_CHANNEL.subscribe
('module.require.error',
FUNC(OBJ, ERROR)) 22.4.0*#OBJ: id 'MODULE', parentFilename 'PATH'
┌────────────────┐
│ ES MODULES │
└────────────────┘
import|export ...
import('URI')->PROMISE #ES modules
import ... from 'URI' #Import from 'URI' not PATH
#Need to be URI encoded
#Must use file:/// if absolute
#Can use fileURLToPath|pathToFileURL() to convert
RESOLUTION ==> #Cannot omit file extension or use index.js
#Use same algorithm to find node_modules (unlike browsers)
SELF IMPORT ==> #Can import current package by name (e.g. in tests)
CACHING ==> #Imports URIs can use #HASH or ?QUERY: included in cache key, providing importing file is ESM
#I.e. can load twice a file by using different ?QUERY
#import('URI') uses the same cache and cache logic
import.meta.url #'file://...'. Should be used instead of __filename|__dirname
23.0.0*#Might include ?QUERY or #HASH, when using --entry-url
import.meta.filename 20.11.0*#Like __filename but for ESM. Same as fileURLToPath(import.meta.url)
20.11.0*#Cannot be used with file imported with 'file://...'
20.11.0*#Resolves symlinks
import.meta.dirname 20.11.0*#Same but for __dirname. Same as dirname(import.meta.filename)
require('module').syncBuiltinESMExports() #Can monkey-patch core modules by modifying their default import.
#This must be called after it so that dynamic import(...) can use it
PACKAGE.exports #'URI'[_ARR]. Like PACKAGE.main except:
# - priority over it
# - must start with '.'
# - only for import|require from 'MODULE[/...]' not relative|absolute paths|URI
#Can be an ARR for fallbacks
# - only skips 'URI' that is not valid identifier with current Node.js version
# - e.g. not starting with '.'
# - i.e. only meant for forward compatibility with new Node.js features
#Used with both CommonJS|ESM
PACKAGE.exports.CONDITION #'URI'[_ARR]. Like PACKAGE.exports except only if CONDITION matches.
#Available CONDITION:
# - require: loaded by require()
# - import: loaded by ES import|import()
20.19.0*# - module-sync: loaded by either require() or ES import|import(), since both can load ESM
# - node: Node.js environment (loaded by require()|import)
# - types[@SEMVER]: TypeScript (version SEMVER)
# - browser: browser environment
# - default: always match, but least priority
# - custom ones, e.g. 'electron', 'deno', etc.
#CONDITION can be nested.
#Matched|tried in object properties order.
--conditions|-C=CONDITION,... #Specify custom CONDITION
PACKAGE.exports.PATH[.CONDITION] #'PATH2'. Like PACKAGE.exports[.CONDITION] except remaps requester's 'URI' to another one
#PATH must start with '.':
# - matched against 'MODULE' in imported path
# - can be single '.'
#PATH must not end with "/"
#PATH is exact match
#PATH+PATH2 can contain wildcard '*':
# - must both contain it
# - if several matches, longer prefixes prevail
#If no matches, errors.
#Forbid any 'MODULE/...' without a matching PACKAGE.exports.PATH
# - including PACKAGE.exports {}|false
PACKAGE.imports.#PATH[.CONDITION] #PATH2. Like PACKAGE.exports but for imports inside the module itself
#Similar goal as IMPORT_MAP but
# - different syntax
# - usable by libraries not only top-level applicaions
DIAGNOSTICS_CHANNEL.subscribe
('module.import.asyncStart|End',
FUNC(OBJ)) 22.4.0*#OBJ: id 'MODULE', parentURL URL
DIAGNOSTICS_CHANNEL.subscribe
('module.import.error',
FUNC(OBJ, ERROR)) 22.4.0*#OBJ: id 'MODULE', parentURL URL
┌────────────┐
│ LOADER │
└────────────┘
--experimental-loader PATH #Customize the behavior of import|import()
#PATH must be ESM, and have a default export LOADER
#When called several times, each LOADER is run, starting from last
# - including the implicit default LOADER, run last
#Each of the methods below:
# - represent one step of the resolution to customize
# - are optional
# - must return either:
# - OBJ2, with OBJ2.shortCircuit true (def: false)
# - the previous LOADERs are not run
# - this moves on the next LOADER phase
# - FUNC(...)
# - the previous LOADERs are then run
# - ... are the current LOADER.*() arguments, except FUNC itself
# - they can be modified
# - this remains in the same LOADER phase, with potentially different arguments
module.register 18.19.0*#Like --experimental-loader but programmatic
('PATH', import.meta.url[, OBJ]) 18.19.0*#Prefer using --import + module.register() than --experimental-loader
module.register(URL[, OBJ]) 18.19.0*#OBJ:
18.19.0*# - data OBJ2:
18.19.0*# - passed to LOADER.initialize()
18.19.0*# - uses structuredClone()
18.19.0*# - transferList VAL_ARR:
18.19.0*# - declare values used in OBJ.data that should be transfered as is
18.19.0*# - e.g. ARRBUFFER[VIEW]|MESSAGEPORT
18.19.0*# - like structuredClone() does
18.19.0*# - parentURL 'URL'
LOADER.initialize(OBJ)[->>] 18.19.0*#Run during --experimental-loader or module.register()
LOADER.resolve('PATH', OBJ, FUNC(...)) #'PATH' is relative path
->>OBJ2 #OBJ:
# - parentURL 'URL'|undefined: absolute base
# - is a URL, e.g. file: protocol with filesystem
# - undefined if entry point, including REPL
# - conditions 'CONDITION'_ARR: from PACKAGE.exports.CONDITION
# - importAttributes OBJ: from import("MDL", { with: OBJ }) or import ... with OBJ
<18.19.0*# - previously called importAssertions, which is kept for backward compatibility but with warning
#OBJ2:
# - url 'URL' (required): resolved absolute URL
# - format: 'module' (ESM), 'commonjs', 'json', 'builtin' (core module), 'wasm'
# - custom formats should use 'module'
# - meant as a hint for LOADER.load()
# - shortCircuit BOOL
# - importAttributes OBJ
LOADER.load('URL', OBJ, FUNC(...)) #'URL': same as returned by LOADER.resolve() OBJ2.url
->>OBJ2 #OBJ:
# - format STR: returned by LOADER.resolve(), i.e. can be undefined
# - conditions, importAttributes: same as LOADER.resolve()
#OBJ2:
# - format (required): like LOADER.resolve()
# - source 'SOURCE'_STR|ARRBUFFER|UINT8_ARR (required): file content
# - shortCircuit BOOL
module.registerHook(OPTS) 23.5.0*#Similar to module.register() but:
23.5.0*# - run in the same thread as loaded file, and can mutate its globalThis
23.5.0*# - sync
OPTS.resolve|load 23.5.0*#LOADER.* but sync
┌───────────────────┐
│ COMPILE CACHE │
└───────────────────┘
ENVVAR NODE_COMPILE_CACHE=DIR 21.1.0*#Caches bytecode to DIR/CACHE_VERSION_HASH/FILE_HASH
21.1.0*#Slower on first run of a file, but faster subsequent startups
21.1.0*#Should not be used together test coverage
enableCompileCache([DIR])->VAL 22.8.0*#Same but, def DIR is ENVVAR NODE_COMPILE_CACHE, or TMP_DIR/node-compile-cache
22.8.0*#Only for dynamic imports, since static imports are already loaded
22.8.0*#Returns OBJ:
22.8.0*# - status constants.compileCacheStatus.*:
22.8.0*# - 'ENABLED': was disabled before
22.8.0*# - 'ALREADY_ENABLED': was already enabled
22.8.0*# - 'FAILED': filesystem issue
22.8.0*# - 'DISABLED': NODE_DISABLE_COMPILE_CACHE=1
22.8.0*# - message 'ERROR': undefined unless 'FAILED'
22.8.0*# - directory 'DIR': undefined if 'FAILED|DISABLED'
ENVVAR NODE_DISABLE_COMPILE_CACHE=1 22.8.0*#
getCompileCacheDir()[->'DIR'] 22.8.0*#
module.flushCompileCache() 22.10.0*#Write any currently buffered bytecode cache right away, instead of on exit
22.10.0*#This allows other processes (including subprocesses) to use it without waiting for current process exit
┌────────────────┐
│ TYPESCRIPT │
└────────────────┘
--experimental-transform-types 22.7.0*#Transform TypeScript types
22.7.0*#Does not do type checking
22.7.0*#Implies --enable-source-maps
22.7.0*#Does not support tsconfig.json-related features, e.g. --paths, --module, etc.
22.7.0*#Supports *.ts|mts|cts but not *.tsx
22.7.0*#Imports must use `type` and specify *.ts file extension (i.e. must use --allowImportingTsExtensions)
TYPES STRIPPING ==> 23.6.0*#By default, does --experimental-transform-types but only ignore types, does not transform them
23.6.0*#I.e. does not support: enums, namespaces, `declare module` parameter properties
23.6.0*#Does not imply --enable-source-maps
--experimental-strip-types 22.6.0-23.5.0*#Required
module.stripTypeScriptTypes
('CODE'[, OPTS])->'CODE' 22.13.0*#Same but on inline 'CODE'
OPTS.mode 22.13.0*#'strip' (def) or 'transform'
OPTS.sourceMap 22.13.0*#BOOL (def: false). Generate a source map, if mode 'transform'
OPTS.sourceUrl 22.13.0*#'URL'. Append sourceURL comment
process.features.typescript 22.10.0*#'strip|transform' when using the above flags
┌─────────────────┐
│ SOURCE MAPS │
└─────────────────┘
--enable-source-maps #Use source maps for ERROR.stack
#Does not work with ERROR.prepareStackTrace()
#Also enables MODULE.findSourceMap|SourceMap
process.setSourceMapsEnabled(BOOL) #Same. Only for files not loaded yet.
# - Current file is already loaded
# - Static imports are all already loaded when this executes, i.e. only
# applies to later dynamic imports
MODULE.setSourceMapsSupport(BOOL[, OBJ]) 23.7.0*#Same but with options OBJ:
23.7.0*# - nodeModules BOOL (def: false): enabled in node_modules
23.7.0*# - generatedCode BOOL (def: false): enabled in eval()
process.sourceMapsEnabled 18.19.0*#BOOL
MODULE.getSourceMapsSupport()->OBJ 23.7.0*#OBJ: enabled BOOL, nodeModules BOOL, generatedCode BOOL
new MODULE.SourceMap(SOURCEMAP_OBJ[, OPTS]) #SOURCEMAP.
#SOURCEMAP_OBJ has source map v3 raw properties
#(version|sources|sourceRoot|sourcesContent|names|file|mappings)
OPTS.lineLengths #NUM_ARR (def: guessed) with char length of each line
SOURCEMAP.payload #SOURCEMAP_OBJ
SOURCEMAP.findEntry(LINE_NUM, COL_NUM)->OBJ #Use "mappings" to map compiled|generated file LINE_NUM|COL_NUM to
#source|original file
#OBJ:
# - generatedLine|Column NUM
# - originalLine|Column NUM
# - originalSource 'SOURCE_PATH'|null
18.18.0*# - name STR: range name
SOURCEMAP.findOrigin(LINE_NUM, COL_NUM) 18.18.0*#Same but in ancestor original file.
->OBJ 18.18.0*#OBJ: fileName STR, lineNumber|columnNumber NUM, name STR
MODULE.findSourceMap('PATH'[, ERROR]) #Parse SOURCEMAP using sourceMappingURL comment (inline or external)
->SOURCEMAP #If inside an Error.prepareStackTrace(ERROR), should specify ERROR for caching reasons
SCRIPT.sourceMapURL 19.1.0*#'URL', if SCRIPT contains sourceMappingURL. undefined otherwise