-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathnodejs.html
More file actions
1185 lines (995 loc) · 64.7 KB
/
nodejs.html
File metadata and controls
1185 lines (995 loc) · 64.7 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Node.js Internals - Better Dev</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header class="topbar">
<button class="sidebar-toggle" aria-label="Open navigation" aria-expanded="false">
<span class="hamburger-icon"></span>
</button>
<a href="index.html" class="logo">Better Dev</a>
</header>
<div class="sidebar-backdrop" aria-hidden="true"></div>
<aside class="sidebar" aria-label="Site navigation">
<div class="sidebar-header">
<span class="sidebar-title">Navigation</span>
<button class="sidebar-close" aria-label="Close navigation">×</button>
</div>
<div class="sidebar-search">
<input type="text" class="sidebar-search-input" placeholder="Search topics..." aria-label="Search topics">
<div class="sidebar-search-results"></div>
</div>
<nav class="sidebar-nav">
<div class="sidebar-group">
<a href="index.html">Home</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Mathematics</div>
<a href="pre-algebra.html">Pre-Algebra</a>
<a href="algebra.html">Algebra</a>
<a href="sequences-series.html">Sequences & Series</a>
<a href="geometry.html">Geometry</a>
<a href="calculus.html">Calculus</a>
<a href="discrete-math.html">Discrete Math</a>
<a href="linear-algebra.html">Linear Algebra</a>
<a href="probability.html">Probability & Statistics</a>
<a href="binary-systems.html">Binary & Number Systems</a>
<a href="number-theory.html">Number Theory for CP</a>
<a href="computational-geometry.html">Computational Geometry</a>
<a href="game-theory.html">Game Theory</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Data Structures & Algorithms</div>
<a href="dsa-foundations.html">DSA Foundations</a>
<a href="arrays.html">Arrays & Strings</a>
<a href="stacks-queues.html">Stacks & Queues</a>
<a href="hashmaps.html">Hash Maps & Sets</a>
<a href="linked-lists.html">Linked Lists</a>
<a href="trees.html">Trees & BST</a>
<a href="graphs.html">Graphs</a>
<a href="sorting.html">Sorting & Searching</a>
<a href="patterns.html">LeetCode Patterns</a>
<a href="dp.html">Dynamic Programming</a>
<a href="advanced.html">Advanced Topics</a>
<a href="string-algorithms.html">String Algorithms</a>
<a href="advanced-graphs.html">Advanced Graphs</a>
<a href="advanced-dp.html">Advanced DP</a>
<a href="advanced-ds.html">Advanced Data Structures</a>
<a href="leetcode-650.html">The 650 Problems</a>
<a href="competitive-programming.html">CP Roadmap</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Languages & Systems</div>
<a href="cpp.html">C++</a>
<a href="golang.html">Go</a>
<a href="javascript.html">JavaScript Deep Dive</a>
<a href="typescript.html">TypeScript</a>
<a href="nodejs.html">Node.js Internals</a>
<a href="os.html">Operating Systems</a>
<a href="linux.html">Linux</a>
<a href="git.html">Git</a>
<a href="backend.html">Backend</a>
<a href="system-design.html">System Design</a>
<a href="networking.html">Networking</a>
<a href="cloud.html">Cloud & Infrastructure</a>
<a href="docker.html">Docker & Compose</a>
<a href="kubernetes.html">Kubernetes</a>
<a href="message-queues.html">Queues & Pub/Sub</a>
<a href="selfhosting.html">VPS & Self-Hosting</a>
<a href="databases.html">PostgreSQL & MySQL</a>
<a href="stripe.html">Stripe & Payments</a>
<a href="distributed-systems.html">Distributed Systems</a>
<a href="backend-engineering.html">Backend Engineering</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">JS/TS Ecosystem</div>
<a href="js-tooling.html">Tooling & Bundlers</a>
<a href="js-testing.html">Testing</a>
<a href="ts-projects.html">Building with TS</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">More</div>
<a href="seans-brain.html">Sean's Brain</a>
</div>
</nav>
</aside>
<div class="container">
<div class="page-header">
<div class="breadcrumb"><a href="index.html">Home</a> / Node.js Internals</div>
<h1>Node.js -- Under the Hood</h1>
<p>Node isn't "just JavaScript on the server." It's V8 + libuv + a massive C++ binding layer that gives you non-blocking I/O, streams, child processes, and worker threads. This page explains how it all fits together.</p>
</div>
<div class="toc">
<h4>Table of Contents</h4>
<a href="#architecture">1. Architecture: V8 + libuv</a>
<a href="#event-loop-phases">2. The Event Loop -- All 6 Phases</a>
<a href="#module-system">3. The Module System (CJS vs ESM)</a>
<a href="#streams">4. Streams</a>
<a href="#buffers">5. Buffers & Binary Data</a>
<a href="#child-process">6. child_process</a>
<a href="#worker-threads">7. Worker Threads</a>
<a href="#cluster">8. Cluster & Scaling</a>
<a href="#fs-path-os">9. fs, path, os -- Core Modules</a>
<a href="#http-internals">10. HTTP Internals</a>
<a href="#error-handling">11. Error Handling & Debugging</a>
<a href="#performance">12. Performance & Profiling</a>
<a href="#concurrency-control">13. Concurrency Control -- p-limit, Semaphores & Resource Pools</a>
</div>
<!-- ───────────── SECTION 1 ───────────── -->
<section id="architecture">
<h2>1. Architecture: V8 + libuv</h2>
<pre><code><span class="lang-label">Text</span>
Your JS Code
|
┌────▼────┐
│ V8 │ ← Compiles & runs your JavaScript
│ Engine │
└────┬────┘
|
┌────▼────────────────────┐
│ Node.js Bindings │ ← C++ glue code (node_api, internal modules)
│ (C++ / N-API) │
└────┬───────────┬────────┘
| |
┌────▼────┐ ┌────▼────┐
│ libuv │ │ c-ares │ ← libuv: async I/O, event loop, thread pool
│ │ │ zlib │ c-ares: async DNS, zlib: compression
│ │ │ openssl│ openssl: TLS/crypto
└─────────┘ └─────────┘
</code></pre>
<div class="tip-box">
<strong>V8</strong> handles JavaScript execution (parsing, compiling, GC). <strong>libuv</strong> handles everything that's async and OS-level: file I/O, networking, DNS, timers, the thread pool. They're connected by Node's C++ binding layer.
</div>
<h3>What libuv Actually Does</h3>
<ul>
<li><strong>Event loop</strong> -- the central mechanism that polls for I/O events</li>
<li><strong>Thread pool</strong> -- 4 threads (default, configurable via <code>UV_THREADPOOL_SIZE</code>) for blocking ops (fs, DNS, crypto)</li>
<li><strong>epoll/kqueue/IOCP</strong> -- OS-specific async I/O mechanisms abstracted by libuv</li>
<li><strong>Handles & Requests</strong> -- long-lived (TCP sockets, timers) vs one-shot (fs read) operations</li>
</ul>
</section>
<!-- ───────────── SECTION 2 ───────────── -->
<section id="event-loop-phases">
<h2>2. The Event Loop -- All 6 Phases</h2>
<p>Node's event loop isn't a simple "check for callbacks" loop. It runs through <strong>6 distinct phases</strong> in order, each with its own queue.</p>
<pre><code><span class="lang-label">Text</span>
┌───────────────────────────┐
┌─>│ timers │ ← setTimeout, setInterval callbacks
│ └──────────┬────────────────┘
│ ┌──────────▼────────────────┐
│ │ pending callbacks │ ← I/O callbacks deferred from previous loop
│ └──────────┬────────────────┘
│ ┌──────────▼────────────────┐
│ │ idle, prepare │ ← internal use only
│ └──────────┬────────────────┘
│ ┌──────────▼────────────────┐
│ │ poll │ ← retrieve new I/O events; execute I/O callbacks
│ └──────────┬────────────────┘ (node blocks here when nothing else to do)
│ ┌──────────▼────────────────┐
│ │ check │ ← setImmediate callbacks
│ └──────────┬────────────────┘
│ ┌──────────▼────────────────┐
│ │ close callbacks │ ← socket.on('close', ...)
│ └──────────┬────────────────┘
└─────────────┘
</code></pre>
<h3>Microtask Queues (Between Every Phase)</h3>
<p>Between each phase, Node drains two microtask queues:</p>
<ol>
<li><strong>process.nextTick()</strong> queue -- always runs first</li>
<li><strong>Promise microtasks</strong> (.then, .catch, .finally, await)</li>
</ol>
<pre><code><span class="lang-label">JavaScript</span>
setTimeout(() => console.log(<span class="string">"1: timer"</span>), <span class="number">0</span>);
setImmediate(() => console.log(<span class="string">"2: immediate"</span>));
process.nextTick(() => console.log(<span class="string">"3: nextTick"</span>));
Promise.resolve().then(() => console.log(<span class="string">"4: promise"</span>));
<span class="comment">// Output: 3: nextTick → 4: promise → 1: timer → 2: immediate</span>
<span class="comment">// (nextTick + promise run before timers phase)</span>
</code></pre>
<div class="warning-box">
<strong>process.nextTick() can starve the event loop.</strong> If you recursively call nextTick, the I/O phase never runs. Use <code>setImmediate()</code> when you want to defer but still let I/O happen.
</div>
</section>
<!-- ───────────── SECTION 3 ───────────── -->
<section id="module-system">
<h2>3. The Module System (CJS vs ESM)</h2>
<h3>CommonJS (CJS) -- The Original</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// CJS: synchronous require, module.exports</span>
<span class="keyword">const</span> fs = require(<span class="string">"fs"</span>);
<span class="keyword">const</span> { readFile } = require(<span class="string">"fs"</span>);
module.exports = { myFunction };
module.exports.myFunction = <span class="keyword">function</span>() {};
exports.myFunction = <span class="keyword">function</span>() {};
</code></pre>
<h3>ES Modules (ESM) -- The Standard</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// ESM: async import, export</span>
<span class="keyword">import</span> fs <span class="keyword">from</span> <span class="string">"node:fs"</span>;
<span class="keyword">import</span> { readFile } <span class="keyword">from</span> <span class="string">"node:fs/promises"</span>;
<span class="keyword">export function</span> <span class="function">myFunction</span>() {}
<span class="keyword">export default</span> <span class="keyword">function</span>() {}
</code></pre>
<h3>How Node Decides CJS vs ESM</h3>
<pre><code><span class="lang-label">Text</span>
.cjs file → always CJS
.mjs file → always ESM
.js file → check nearest package.json "type" field:
"type": "module" → ESM
"type": "commonjs" → CJS (default if omitted)
</code></pre>
<div class="tip-box">
<strong>The <code>node:</code> prefix</strong> (e.g., <code>import fs from "node:fs"</code>) explicitly tells Node this is a built-in module. It prevents name collisions with npm packages and is the recommended way to import built-ins.
</div>
<h3>Key Differences</h3>
<pre><code><span class="lang-label">Text</span>
Feature CJS ESM
─────────────────────────────────────────────────────
Loading Synchronous Asynchronous
Top-level await ❌ ✅
this at top module.exports undefined
__filename ✅ available ❌ use import.meta.url
__dirname ✅ available ❌ use import.meta.dirname (v21+)
require() ✅ ❌ (use createRequire as escape hatch)
import ❌ static ✅
import() ✅ dynamic ✅ dynamic
Circular deps Partial exports Live bindings (resolved)
</code></pre>
<h3>import.meta in ESM</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// Get __filename and __dirname equivalents in ESM</span>
<span class="keyword">import</span> { fileURLToPath } <span class="keyword">from</span> <span class="string">"node:url"</span>;
<span class="keyword">import</span> { dirname } <span class="keyword">from</span> <span class="string">"node:path"</span>;
<span class="keyword">const</span> __filename = <span class="function">fileURLToPath</span>(import.meta.url);
<span class="keyword">const</span> __dirname = <span class="function">dirname</span>(__filename);
<span class="comment">// Node 21+: import.meta.dirname and import.meta.filename</span>
</code></pre>
</section>
<!-- ───────────── SECTION 4 ───────────── -->
<section id="streams">
<h2>4. Streams</h2>
<p>Streams let you process data <strong>piece by piece</strong> instead of loading everything into memory. There are 4 types.</p>
<pre><code><span class="lang-label">Text</span>
Type Description Example
─────────────────────────────────────────────────────
Readable Data source you read from fs.createReadStream, http req
Writable Data sink you write to fs.createWriteStream, http res
Duplex Both readable + writable net.Socket, TCP connection
Transform Duplex that modifies data zlib.createGzip, crypto
</code></pre>
<h3>Piping (The Main Pattern)</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">import</span> { createReadStream, createWriteStream } <span class="keyword">from</span> <span class="string">"node:fs"</span>;
<span class="keyword">import</span> { createGzip } <span class="keyword">from</span> <span class="string">"node:zlib"</span>;
<span class="keyword">import</span> { pipeline } <span class="keyword">from</span> <span class="string">"node:stream/promises"</span>;
<span class="comment">// Compress a file: read → gzip → write</span>
<span class="keyword">await</span> <span class="function">pipeline</span>(
<span class="function">createReadStream</span>(<span class="string">"input.txt"</span>),
<span class="function">createGzip</span>(),
<span class="function">createWriteStream</span>(<span class="string">"input.txt.gz"</span>)
);
</code></pre>
<div class="warning-box">
<strong>Always use <code>pipeline()</code></strong> instead of <code>.pipe()</code>. The old <code>.pipe()</code> method doesn't handle errors or cleanup properly. <code>pipeline</code> propagates errors and destroys streams when done.
</div>
<h3>Creating a Custom Transform Stream</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">import</span> { Transform } <span class="keyword">from</span> <span class="string">"node:stream"</span>;
<span class="keyword">const</span> upperCase = <span class="keyword">new</span> <span class="function">Transform</span>({
<span class="function">transform</span>(chunk, encoding, callback) {
<span class="keyword">this</span>.push(chunk.toString().toUpperCase());
<span class="function">callback</span>();
}
});
process.stdin.pipe(upperCase).pipe(process.stdout);
</code></pre>
<h3>Readable Streams with async iteration</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">import</span> { createReadStream } <span class="keyword">from</span> <span class="string">"node:fs"</span>;
<span class="keyword">const</span> stream = <span class="function">createReadStream</span>(<span class="string">"big-file.txt"</span>, { encoding: <span class="string">"utf8"</span> });
<span class="keyword">for await</span> (<span class="keyword">const</span> chunk <span class="keyword">of</span> stream) {
console.log(<span class="string">`Got ${chunk.length} chars`</span>);
}
</code></pre>
</section>
<!-- ───────────── SECTION 5 ───────────── -->
<section id="buffers">
<h2>5. Buffers & Binary Data</h2>
<p>A <code>Buffer</code> is a fixed-size chunk of raw memory, outside the V8 heap. It's how Node handles binary data (files, network packets, images).</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// Creating buffers</span>
<span class="keyword">const</span> b1 = Buffer.alloc(<span class="number">10</span>); <span class="comment">// 10 zero-filled bytes</span>
<span class="keyword">const</span> b2 = Buffer.from(<span class="string">"hello"</span>); <span class="comment">// from string (UTF-8)</span>
<span class="keyword">const</span> b3 = Buffer.from([<span class="number">0x48</span>, <span class="number">0x69</span>]); <span class="comment">// from byte array → "Hi"</span>
<span class="keyword">const</span> b4 = Buffer.from(<span class="string">"aGVsbG8="</span>, <span class="string">"base64"</span>); <span class="comment">// from base64</span>
<span class="comment">// Converting</span>
b2.toString(<span class="string">"utf8"</span>); <span class="comment">// "hello"</span>
b2.toString(<span class="string">"hex"</span>); <span class="comment">// "68656c6c6f"</span>
b2.toString(<span class="string">"base64"</span>); <span class="comment">// "aGVsbG8="</span>
<span class="comment">// Buffer is a Uint8Array subclass</span>
b2[<span class="number">0</span>]; <span class="comment">// 104 (ASCII 'h')</span>
b2.length; <span class="comment">// 5 bytes</span>
b2.slice(<span class="number">0</span>, <span class="number">2</span>); <span class="comment">// Buffer containing "he" (shares memory!)</span>
</code></pre>
<div class="tip-box">
<strong>Buffer.alloc() vs Buffer.allocUnsafe():</strong> <code>alloc</code> zeroes memory (safe), <code>allocUnsafe</code> skips zeroing (faster but may contain old data). Use <code>alloc</code> unless you have a performance reason and will overwrite all bytes.
</div>
</section>
<!-- ───────────── SECTION 6 ───────────── -->
<section id="child-process">
<h2>6. child_process</h2>
<p>Run external commands or spawn new Node processes. Four main functions.</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">import</span> { exec, execFile, spawn, fork } <span class="keyword">from</span> <span class="string">"node:child_process"</span>;
<span class="comment">// exec: runs in a SHELL, buffers entire output</span>
<span class="function">exec</span>(<span class="string">"ls -la | grep .js"</span>, (err, stdout, stderr) => {
console.log(stdout);
});
<span class="comment">// execFile: no shell, safer, still buffers output</span>
<span class="function">execFile</span>(<span class="string">"git"</span>, [<span class="string">"status"</span>], (err, stdout) => {
console.log(stdout);
});
<span class="comment">// spawn: no shell, STREAMS output (best for large output)</span>
<span class="keyword">const</span> child = <span class="function">spawn</span>(<span class="string">"git"</span>, [<span class="string">"log"</span>, <span class="string">"--oneline"</span>]);
child.stdout.on(<span class="string">"data"</span>, (chunk) => console.log(chunk.toString()));
child.on(<span class="string">"close"</span>, (code) => console.log(<span class="string">`exited ${code}`</span>));
<span class="comment">// fork: spawn a new NODE process with IPC channel</span>
<span class="keyword">const</span> worker = <span class="function">fork</span>(<span class="string">"./worker.js"</span>);
worker.send({ task: <span class="string">"compute"</span> });
worker.on(<span class="string">"message"</span>, (result) => console.log(result));
</code></pre>
<h3>Promise-based (Node 16+)</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">import</span> { execFile } <span class="keyword">from</span> <span class="string">"node:child_process"</span>;
<span class="keyword">import</span> { promisify } <span class="keyword">from</span> <span class="string">"node:util"</span>;
<span class="keyword">const</span> execFileAsync = <span class="function">promisify</span>(execFile);
<span class="keyword">const</span> { stdout } = <span class="keyword">await</span> <span class="function">execFileAsync</span>(<span class="string">"git"</span>, [<span class="string">"status"</span>]);
</code></pre>
<pre><code><span class="lang-label">Text</span>
Function Shell? Output IPC? Best For
────────────────────────────────────────────────────────
exec ✅ yes Buffered ❌ Quick shell commands
execFile ❌ no Buffered ❌ Running binaries safely
spawn ❌ no Streamed ❌ Large output, long processes
fork ❌ no Streamed ✅ Node-to-Node communication
</code></pre>
</section>
<!-- ───────────── SECTION 7 ───────────── -->
<section id="worker-threads">
<h2>7. Worker Threads</h2>
<p>Worker threads run JavaScript in <strong>separate V8 isolates</strong> within the same process. Unlike child_process, they share memory via <code>SharedArrayBuffer</code>.</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// main.js</span>
<span class="keyword">import</span> { Worker } <span class="keyword">from</span> <span class="string">"node:worker_threads"</span>;
<span class="keyword">const</span> worker = <span class="keyword">new</span> <span class="function">Worker</span>(<span class="string">"./heavy-task.js"</span>, {
workerData: { iterations: <span class="number">1_000_000</span> }
});
worker.on(<span class="string">"message"</span>, (result) => console.log(<span class="string">"Result:"</span>, result));
worker.on(<span class="string">"error"</span>, (err) => console.error(err));
worker.on(<span class="string">"exit"</span>, (code) => console.log(<span class="string">"Worker exited"</span>, code));
</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// heavy-task.js</span>
<span class="keyword">import</span> { workerData, parentPort } <span class="keyword">from</span> <span class="string">"node:worker_threads"</span>;
<span class="keyword">let</span> sum = <span class="number">0</span>;
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < workerData.iterations; i++) {
sum += Math.sqrt(i);
}
parentPort.postMessage(sum);
</code></pre>
<div class="example-box">
<strong>When to use Worker Threads vs child_process:</strong>
<ul>
<li><strong>Worker Threads</strong> -- CPU-heavy JS work (hashing, parsing, math). Shares memory, lower overhead.</li>
<li><strong>child_process</strong> -- Running external binaries, isolating untrusted code, or when you need a full separate process.</li>
</ul>
</div>
</section>
<!-- ───────────── SECTION 8 ───────────── -->
<section id="cluster">
<h2>8. Cluster & Scaling</h2>
<p>The <code>cluster</code> module forks multiple Node processes that share the same server port. This lets you use all CPU cores.</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">import</span> cluster <span class="keyword">from</span> <span class="string">"node:cluster"</span>;
<span class="keyword">import</span> { cpus } <span class="keyword">from</span> <span class="string">"node:os"</span>;
<span class="keyword">import</span> http <span class="keyword">from</span> <span class="string">"node:http"</span>;
<span class="keyword">if</span> (cluster.isPrimary) {
<span class="keyword">const</span> numCPUs = <span class="function">cpus</span>().length;
console.log(<span class="string">`Primary ${process.pid} forking ${numCPUs} workers`</span>);
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < numCPUs; i++) {
cluster.fork();
}
cluster.on(<span class="string">"exit"</span>, (worker) => {
console.log(<span class="string">`Worker ${worker.process.pid} died, restarting...`</span>);
cluster.fork(); <span class="comment">// auto-restart</span>
});
} <span class="keyword">else</span> {
http.<span class="function">createServer</span>((req, res) => {
res.end(<span class="string">`Handled by worker ${process.pid}\n`</span>);
}).listen(<span class="number">3000</span>);
}
</code></pre>
<div class="tip-box">
<strong>In production, use PM2</strong> instead of rolling your own cluster code. <code>pm2 start app.js -i max</code> handles forking, restarting, log management, and zero-downtime reloads.
</div>
</section>
<!-- ───────────── SECTION 9 ───────────── -->
<section id="fs-path-os">
<h2>9. fs, path, os -- Core Modules</h2>
<h3>File System (fs)</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">import</span> { readFile, writeFile, mkdir, readdir, stat, rm } <span class="keyword">from</span> <span class="string">"node:fs/promises"</span>;
<span class="comment">// Always use fs/promises (not callback-based fs)</span>
<span class="keyword">const</span> content = <span class="keyword">await</span> <span class="function">readFile</span>(<span class="string">"./data.json"</span>, <span class="string">"utf8"</span>);
<span class="keyword">const</span> data = JSON.parse(content);
<span class="keyword">await</span> <span class="function">writeFile</span>(<span class="string">"./output.json"</span>, JSON.stringify(data, <span class="keyword">null</span>, <span class="number">2</span>));
<span class="keyword">await</span> <span class="function">mkdir</span>(<span class="string">"./nested/dirs"</span>, { recursive: <span class="keyword">true</span> });
<span class="comment">// List directory</span>
<span class="keyword">const</span> files = <span class="keyword">await</span> <span class="function">readdir</span>(<span class="string">"./src"</span>, { withFileTypes: <span class="keyword">true</span> });
<span class="keyword">for</span> (<span class="keyword">const</span> f <span class="keyword">of</span> files) {
console.log(f.name, f.isDirectory() ? <span class="string">"dir"</span> : <span class="string">"file"</span>);
}
<span class="comment">// Watch for changes</span>
<span class="keyword">import</span> { watch } <span class="keyword">from</span> <span class="string">"node:fs/promises"</span>;
<span class="keyword">for await</span> (<span class="keyword">const</span> event <span class="keyword">of</span> <span class="function">watch</span>(<span class="string">"./src"</span>)) {
console.log(event.eventType, event.filename);
}
</code></pre>
<h3>Path</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">import</span> path <span class="keyword">from</span> <span class="string">"node:path"</span>;
path.join(<span class="string">"/users"</span>, <span class="string">"sean"</span>, <span class="string">"docs"</span>); <span class="comment">// "/users/sean/docs"</span>
path.resolve(<span class="string">"./src"</span>, <span class="string">"index.ts"</span>); <span class="comment">// absolute path</span>
path.basename(<span class="string">"/a/b/file.ts"</span>); <span class="comment">// "file.ts"</span>
path.extname(<span class="string">"file.ts"</span>); <span class="comment">// ".ts"</span>
path.dirname(<span class="string">"/a/b/file.ts"</span>); <span class="comment">// "/a/b"</span>
path.parse(<span class="string">"/a/b/file.ts"</span>); <span class="comment">// { root, dir, base, ext, name }</span>
</code></pre>
<h3>OS</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">import</span> os <span class="keyword">from</span> <span class="string">"node:os"</span>;
os.cpus().length; <span class="comment">// number of CPU cores</span>
os.totalmem(); <span class="comment">// total RAM in bytes</span>
os.freemem(); <span class="comment">// free RAM</span>
os.homedir(); <span class="comment">// "/home/sean"</span>
os.tmpdir(); <span class="comment">// "/tmp"</span>
os.platform(); <span class="comment">// "linux", "darwin", "win32"</span>
os.hostname(); <span class="comment">// machine hostname</span>
</code></pre>
</section>
<!-- ───────────── SECTION 10 ───────────── -->
<section id="http-internals">
<h2>10. HTTP Internals</h2>
<p>Node's built-in <code>http</code> module is what Express, Fastify, and Hono all build on top of.</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">import</span> http <span class="keyword">from</span> <span class="string">"node:http"</span>;
<span class="keyword">const</span> server = http.<span class="function">createServer</span>((req, res) => {
<span class="comment">// req is a Readable stream</span>
<span class="comment">// res is a Writable stream</span>
console.log(req.method, req.url, req.headers);
<span class="keyword">if</span> (req.method === <span class="string">"POST"</span>) {
<span class="keyword">const</span> chunks = [];
req.on(<span class="string">"data"</span>, (chunk) => chunks.push(chunk));
req.on(<span class="string">"end"</span>, () => {
<span class="keyword">const</span> body = Buffer.concat(chunks).toString();
res.writeHead(<span class="number">200</span>, { <span class="string">"Content-Type"</span>: <span class="string">"application/json"</span> });
res.end(JSON.stringify({ received: body }));
});
} <span class="keyword">else</span> {
res.writeHead(<span class="number">200</span>, { <span class="string">"Content-Type"</span>: <span class="string">"text/plain"</span> });
res.end(<span class="string">"Hello World"</span>);
}
});
server.listen(<span class="number">3000</span>, () => console.log(<span class="string">"Listening on :3000"</span>));
</code></pre>
<h3>Making HTTP Requests (fetch is built-in now)</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// Node 18+: global fetch (uses undici under the hood)</span>
<span class="keyword">const</span> res = <span class="keyword">await</span> <span class="function">fetch</span>(<span class="string">"https://api.github.com/users/sean"</span>);
<span class="keyword">const</span> data = <span class="keyword">await</span> res.json();
</code></pre>
</section>
<!-- ───────────── SECTION 11 ───────────── -->
<section id="error-handling">
<h2>11. Error Handling & Debugging</h2>
<h3>Error Types</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// Operational errors -- expected failures (file not found, network timeout)</span>
<span class="keyword">try</span> {
<span class="keyword">await</span> readFile(<span class="string">"missing.txt"</span>);
} <span class="keyword">catch</span> (err) {
<span class="keyword">if</span> (err.code === <span class="string">"ENOENT"</span>) console.log(<span class="string">"File not found"</span>);
}
<span class="comment">// Programmer errors -- bugs (TypeError, null reference)</span>
<span class="comment">// These should crash the process (fix the bug, don't catch it)</span>
</code></pre>
<h3>Global Error Handlers</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// Uncaught exception -- something threw and nobody caught it</span>
process.on(<span class="string">"uncaughtException"</span>, (err) => {
console.error(<span class="string">"UNCAUGHT:"</span>, err);
process.exit(<span class="number">1</span>); <span class="comment">// always exit -- state may be corrupt</span>
});
<span class="comment">// Unhandled promise rejection</span>
process.on(<span class="string">"unhandledRejection"</span>, (reason) => {
console.error(<span class="string">"UNHANDLED REJECTION:"</span>, reason);
process.exit(<span class="number">1</span>);
});
</code></pre>
<h3>Debugging</h3>
<pre><code><span class="lang-label">Bash</span>
<span class="comment"># Built-in inspector (open chrome://inspect)</span>
node --inspect src/index.js
<span class="comment"># Break on first line</span>
node --inspect-brk src/index.js
<span class="comment"># Print memory usage</span>
node -e "console.log(process.memoryUsage())"
</code></pre>
</section>
<!-- ───────────── SECTION 12 ───────────── -->
<section id="performance">
<h2>12. Performance & Profiling</h2>
<h3>process.hrtime.bigint() for Benchmarking</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">const</span> start = process.hrtime.bigint();
<span class="comment">// ... do work ...</span>
<span class="keyword">const</span> end = process.hrtime.bigint();
console.log(<span class="string">`Took ${Number(end - start) / 1e6}ms`</span>);
</code></pre>
<h3>Performance Hooks</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">import</span> { performance, PerformanceObserver } <span class="keyword">from</span> <span class="string">"node:perf_hooks"</span>;
performance.mark(<span class="string">"start"</span>);
<span class="comment">// ... do work ...</span>
performance.mark(<span class="string">"end"</span>);
performance.measure(<span class="string">"my-op"</span>, <span class="string">"start"</span>, <span class="string">"end"</span>);
<span class="keyword">const</span> [entry] = performance.getEntriesByName(<span class="string">"my-op"</span>);
console.log(<span class="string">`Took ${entry.duration}ms`</span>);
</code></pre>
<h3>CPU Profiling</h3>
<pre><code><span class="lang-label">Bash</span>
<span class="comment"># Generate a CPU profile (load it in Chrome DevTools)</span>
node --cpu-prof src/index.js
<span class="comment"># Heap snapshot for memory leaks</span>
node --heap-prof src/index.js
<span class="comment"># Trace garbage collection</span>
node --trace-gc src/index.js
</code></pre>
<div class="tip-box">
<strong>Common performance killers in Node:</strong>
<ul>
<li>Synchronous I/O (<code>fs.readFileSync</code>) on the main thread</li>
<li>Blocking the event loop with CPU-heavy work (use worker threads)</li>
<li>Creating too many closures or callbacks (memory pressure)</li>
<li>Not streaming large payloads (buffering entire files in memory)</li>
</ul>
</div>
</section>
<!-- ───────────── SECTION 13 ───────────── -->
<section id="concurrency-control">
<h2>13. Concurrency Control -- p-limit, Semaphores & Resource Pools</h2>
<h3>Why Node Needs Concurrency Control</h3>
<p>Node is single-threaded, but it handles <strong>many concurrent I/O operations</strong> at once. That's usually a strength -- until you accidentally launch 10,000 file reads or HTTP requests simultaneously and overwhelm the system.</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// This looks innocent but will crash on large arrays</span>
<span class="keyword">const</span> files = <span class="keyword">await</span> <span class="function">getFileList</span>(); <span class="comment">// 10,000 files</span>
<span class="keyword">const</span> results = <span class="keyword">await</span> Promise.all(
files.map(f => readFile(f, <span class="string">"utf8"</span>))
); <span class="comment">// BOOM: EMFILE -- too many open files</span>
</code></pre>
<div class="warning-box">
<strong>What goes wrong when you don't limit concurrency:</strong>
<ul>
<li><strong>EMFILE</strong> -- OS file descriptor limit (typically 1024 on Linux)</li>
<li><strong>ECONNRESET / ETIMEDOUT</strong> -- too many TCP connections at once</li>
<li><strong>API rate limits</strong> -- external services return 429 Too Many Requests</li>
<li><strong>Thread pool starvation</strong> -- libuv's thread pool only has 4 threads by default, so 10,000 <code>fs.readFile</code> calls queue up massively</li>
<li><strong>Memory exhaustion</strong> -- thousands of in-flight buffers pile up in memory</li>
</ul>
</div>
<div class="formula-box">
<strong>The core idea:</strong> Instead of <code>Promise.all(everything)</code>, run at most N operations at a time. When one finishes, start the next. This is <strong>concurrency limiting</strong>.
</div>
<h3>p-limit -- Concurrency Limiter</h3>
<p>The <code>p-limit</code> npm package is the standard tool for this. It wraps async functions so that only N run concurrently.</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">import</span> pLimit <span class="keyword">from</span> <span class="string">"p-limit"</span>;
<span class="keyword">import</span> { readFile } <span class="keyword">from</span> <span class="string">"node:fs/promises"</span>;
<span class="keyword">const</span> limit = <span class="function">pLimit</span>(<span class="number">10</span>); <span class="comment">// max 10 concurrent operations</span>
<span class="keyword">const</span> files = <span class="keyword">await</span> <span class="function">getFileList</span>(); <span class="comment">// 1000 files</span>
<span class="comment">// All 1000 are "scheduled" but only 10 run at a time</span>
<span class="keyword">const</span> results = <span class="keyword">await</span> Promise.all(
files.map(f => <span class="function">limit</span>(() => readFile(f, <span class="string">"utf8"</span>)))
);
</code></pre>
<h3>Build p-limit From Scratch</h3>
<p>Understanding how it works under the hood is more valuable than just using the package. The core is a queue + counter.</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">pLimit</span>(concurrency) {
<span class="keyword">let</span> active = <span class="number">0</span>;
<span class="keyword">const</span> queue = [];
<span class="keyword">function</span> <span class="function">next</span>() {
<span class="keyword">if</span> (active >= concurrency || queue.length === <span class="number">0</span>) <span class="keyword">return</span>;
active++;
<span class="keyword">const</span> { fn, resolve, reject } = queue.shift();
<span class="function">fn</span>().then(resolve, reject).finally(() => {
active--;
<span class="function">next</span>();
});
}
<span class="keyword">return function</span> <span class="function">limit</span>(fn) {
<span class="keyword">return new</span> Promise((resolve, reject) => {
queue.push({ fn, resolve, reject });
<span class="function">next</span>();
});
};
}
<span class="comment">// Usage -- identical to the npm package</span>
<span class="keyword">const</span> limit = <span class="function">pLimit</span>(<span class="number">5</span>);
<span class="keyword">const</span> results = <span class="keyword">await</span> Promise.all(
urls.map(url => <span class="function">limit</span>(() => <span class="function">fetch</span>(url)))
);
</code></pre>
<div class="tip-box">
<strong>How it works step by step:</strong>
<ol>
<li><code>limit(fn)</code> pushes the task onto a queue and returns a promise</li>
<li><code>next()</code> checks if we're under the concurrency cap</li>
<li>If yes, it dequeues a task, runs it, and increments <code>active</code></li>
<li>When the task finishes (<code>.finally</code>), it decrements <code>active</code> and calls <code>next()</code> again</li>
<li>This creates a self-sustaining pipeline -- always N tasks running until the queue is empty</li>
</ol>
</div>
<h3>Real Example: Reading 1000 Files with Concurrency of 10</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">import</span> { readFile, readdir } <span class="keyword">from</span> <span class="string">"node:fs/promises"</span>;
<span class="keyword">import</span> { join } <span class="keyword">from</span> <span class="string">"node:path"</span>;
<span class="keyword">function</span> <span class="function">pLimit</span>(concurrency) {
<span class="keyword">let</span> active = <span class="number">0</span>;
<span class="keyword">const</span> queue = [];
<span class="keyword">function</span> <span class="function">next</span>() {
<span class="keyword">if</span> (active >= concurrency || queue.length === <span class="number">0</span>) <span class="keyword">return</span>;
active++;
<span class="keyword">const</span> { fn, resolve, reject } = queue.shift();
<span class="function">fn</span>().then(resolve, reject).finally(() => { active--; <span class="function">next</span>(); });
}
<span class="keyword">return</span> (fn) => <span class="keyword">new</span> Promise((resolve, reject) => {
queue.push({ fn, resolve, reject });
<span class="function">next</span>();
});
}
<span class="keyword">async function</span> <span class="function">processAllFiles</span>(dir) {
<span class="keyword">const</span> entries = <span class="keyword">await</span> <span class="function">readdir</span>(dir);
<span class="keyword">const</span> limit = <span class="function">pLimit</span>(<span class="number">10</span>); <span class="comment">// only 10 files open at a time</span>
<span class="keyword">const</span> contents = <span class="keyword">await</span> Promise.all(
entries.map(name =>
<span class="function">limit</span>(() => readFile(join(dir, name), <span class="string">"utf8"</span>))
)
);
console.log(<span class="string">`Read ${contents.length} files`</span>);
<span class="keyword">return</span> contents;
}
</code></pre>
<h3>Semaphore Pattern</h3>
<p>A <strong>semaphore</strong> is the classic computer science primitive behind concurrency limiting. It's a counter with two operations: <code>acquire()</code> (decrement and wait if zero) and <code>release()</code> (increment and wake up a waiter). This gives you more control than p-limit when you need to hold a resource across multiple async steps.</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">class</span> <span class="function">Semaphore</span> {
<span class="function">constructor</span>(max) {
<span class="keyword">this</span>.max = max;
<span class="keyword">this</span>.active = <span class="number">0</span>;
<span class="keyword">this</span>.waiters = [];
}
<span class="keyword">async</span> <span class="function">acquire</span>() {
<span class="keyword">if</span> (<span class="keyword">this</span>.active < <span class="keyword">this</span>.max) {
<span class="keyword">this</span>.active++;
<span class="keyword">return</span>;
}
<span class="comment">// At capacity -- wait until someone releases</span>
<span class="keyword">await new</span> Promise(resolve => <span class="keyword">this</span>.waiters.push(resolve));
}
<span class="function">release</span>() {
<span class="keyword">if</span> (<span class="keyword">this</span>.waiters.length > <span class="number">0</span>) {
<span class="comment">// Wake up the next waiter (they get our slot)</span>
<span class="keyword">const</span> next = <span class="keyword">this</span>.waiters.shift();
<span class="function">next</span>();
} <span class="keyword">else</span> {
<span class="keyword">this</span>.active--;
}
}
}
<span class="comment">// Usage</span>
<span class="keyword">const</span> sem = <span class="keyword">new</span> <span class="function">Semaphore</span>(<span class="number">5</span>);
<span class="keyword">async function</span> <span class="function">doWork</span>(item) {
<span class="keyword">await</span> sem.<span class="function">acquire</span>();
<span class="keyword">try</span> {
<span class="comment">// ... do async work with the resource ...</span>
<span class="keyword">await</span> <span class="function">processItem</span>(item);
} <span class="keyword">finally</span> {
sem.<span class="function">release</span>(); <span class="comment">// always release, even on error</span>
}
}
<span class="comment">// Launch many tasks -- only 5 run concurrently</span>
<span class="keyword">await</span> Promise.all(items.map(item => <span class="function">doWork</span>(item)));
</code></pre>
<div class="example-box">
<strong>p-limit vs Semaphore -- when to use which:</strong>
<ul>
<li><strong>p-limit</strong> -- when each task is a single async function call. Simpler API.</li>
<li><strong>Semaphore</strong> -- when you need to hold the "slot" across multiple await points (e.g., acquire a DB connection, run 3 queries, then release). The <code>acquire/release</code> pattern gives you explicit control.</li>
</ul>
</div>
<h3>Resource Pool</h3>
<p>A <strong>resource pool</strong> is a pre-allocated set of reusable resources (database connections, worker threads, etc). Instead of creating a new connection for every request (expensive), you check one out from the pool and return it when done.</p>
<div class="formula-box">
<strong>Why pooling matters:</strong> Creating a PostgreSQL connection takes ~50-100ms (TCP handshake + TLS + auth). Reusing one from a pool takes ~0ms. With 1000 requests/sec, that's the difference between working and melting.
</div>
<h3>Build a Simple Generic Resource Pool From Scratch</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">class</span> <span class="function">Pool</span> {
<span class="function">constructor</span>({ create, destroy, max = <span class="number">10</span> }) {
<span class="keyword">this</span>.create = create; <span class="comment">// factory: () => Promise<Resource></span>
<span class="keyword">this</span>.destroy = destroy; <span class="comment">// cleanup: (resource) => Promise<void></span>
<span class="keyword">this</span>.max = max;
<span class="keyword">this</span>.available = []; <span class="comment">// idle resources ready for reuse</span>
<span class="keyword">this</span>.size = <span class="number">0</span>; <span class="comment">// total created (available + in-use)</span>
<span class="keyword">this</span>.waiters = []; <span class="comment">// callers waiting for a resource</span>
}
<span class="keyword">async</span> <span class="function">acquire</span>() {
<span class="comment">// 1. Reuse an idle resource if available</span>
<span class="keyword">if</span> (<span class="keyword">this</span>.available.length > <span class="number">0</span>) {
<span class="keyword">return</span> <span class="keyword">this</span>.available.pop();
}
<span class="comment">// 2. Create a new one if under the limit</span>
<span class="keyword">if</span> (<span class="keyword">this</span>.size < <span class="keyword">this</span>.max) {
<span class="keyword">this</span>.size++;
<span class="keyword">return await</span> <span class="keyword">this</span>.<span class="function">create</span>();
}
<span class="comment">// 3. At capacity -- wait for one to be released</span>
<span class="keyword">return new</span> Promise(resolve => <span class="keyword">this</span>.waiters.push(resolve));
}
<span class="function">release</span>(resource) {
<span class="keyword">if</span> (<span class="keyword">this</span>.waiters.length > <span class="number">0</span>) {
<span class="comment">// Hand directly to a waiting caller</span>
<span class="keyword">const</span> next = <span class="keyword">this</span>.waiters.shift();
<span class="function">next</span>(resource);
} <span class="keyword">else</span> {
<span class="comment">// No one waiting -- put back in the idle list</span>
<span class="keyword">this</span>.available.push(resource);
}
}
<span class="keyword">async</span> <span class="function">drain</span>() {
<span class="comment">// Destroy all idle resources (for graceful shutdown)</span>
<span class="keyword">for</span> (<span class="keyword">const</span> r <span class="keyword">of</span> <span class="keyword">this</span>.available) {
<span class="keyword">await</span> <span class="keyword">this</span>.<span class="function">destroy</span>(r);
}
<span class="keyword">this</span>.available = [];
}
}
</code></pre>
<h3>Using the Pool</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">const</span> pool = <span class="keyword">new</span> <span class="function">Pool</span>({
create: <span class="keyword">async</span> () => {
console.log(<span class="string">"Creating new DB connection..."</span>);
<span class="keyword">return await</span> <span class="function">connectToDatabase</span>();
},
destroy: <span class="keyword">async</span> (conn) => {
<span class="keyword">await</span> conn.<span class="function">close</span>();
},
max: <span class="number">20</span>
});
<span class="keyword">async function</span> <span class="function">handleRequest</span>(req) {
<span class="keyword">const</span> conn = <span class="keyword">await</span> pool.<span class="function">acquire</span>();
<span class="keyword">try</span> {
<span class="keyword">const</span> rows = <span class="keyword">await</span> conn.<span class="function">query</span>(<span class="string">"SELECT * FROM users WHERE id = $1"</span>, [req.userId]);
<span class="keyword">return</span> rows;
} <span class="keyword">finally</span> {
pool.<span class="function">release</span>(conn); <span class="comment">// always return to pool</span>
}
}
</code></pre>
<h3>generic-pool npm Package</h3>
<p>For production, the <code>generic-pool</code> package adds idle timeouts, validation, min/max sizing, and priority queuing.</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">import</span> { createPool } <span class="keyword">from</span> <span class="string">"generic-pool"</span>;
<span class="keyword">const</span> pool = <span class="function">createPool</span>({
<span class="keyword">async</span> <span class="function">create</span>() {
<span class="keyword">return await</span> <span class="function">connectToDatabase</span>();
},
<span class="keyword">async</span> <span class="function">destroy</span>(conn) {
<span class="keyword">await</span> conn.<span class="function">close</span>();
}
}, {
min: <span class="number">2</span>, <span class="comment">// keep 2 idle connections warm</span>
max: <span class="number">20</span>, <span class="comment">// never exceed 20 connections</span>
idleTimeoutMillis: <span class="number">30000</span> <span class="comment">// destroy idle connections after 30s</span>
});
<span class="keyword">const</span> conn = <span class="keyword">await</span> pool.<span class="function">acquire</span>();
<span class="keyword">try</span> {
<span class="keyword">await</span> conn.<span class="function">query</span>(<span class="string">"..."</span>);
} <span class="keyword">finally</span> {
pool.<span class="function">release</span>(conn);
}
<span class="comment">// Graceful shutdown</span>
<span class="keyword">await</span> pool.<span class="function">drain</span>();
pool.<span class="function">clear</span>();
</code></pre>
<h3>Database Connection Pools (pg.Pool)</h3>
<p>Most database drivers have built-in pooling. PostgreSQL's <code>pg</code> module is the canonical example.</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">import</span> pg <span class="keyword">from</span> <span class="string">"pg"</span>;
<span class="keyword">const</span> pool = <span class="keyword">new</span> pg.<span class="function">Pool</span>({
host: <span class="string">"localhost"</span>,
port: <span class="number">5432</span>,
database: <span class="string">"myapp"</span>,
user: <span class="string">"sean"</span>,
password: process.env.DB_PASSWORD,
max: <span class="number">20</span>, <span class="comment">// max connections in pool</span>
idleTimeoutMillis: <span class="number">30000</span>, <span class="comment">// close idle connections after 30s</span>
connectionTimeoutMillis: <span class="number">2000</span> <span class="comment">// fail if can't connect in 2s</span>
});
<span class="comment">// Option 1: auto-acquire and release</span>
<span class="keyword">const</span> { rows } = <span class="keyword">await</span> pool.<span class="function">query</span>(<span class="string">"SELECT * FROM users WHERE id = $1"</span>, [<span class="number">42</span>]);