Lessons in this course (11)

1. What Node.js is — V8, libuv and the single-threaded event loop

Basic★ Must knowLesson 1 of 11
text
Your JavaScript
     │
┌────▼─────────────── Node.js ────────────────────────────┐
│ Core modules (fs, http, crypto, stream …) — JS + C++ bindings │
├───────────────┬──────────────────────────────────────────┤
│ V8            │ libuv                                     │
│ JS engine:    │ event loop, non-blocking network I/O,      │
│ parse, JIT,   │ thread pool (fs, dns.lookup, crypto, zlib),│
│ GC            │ timers, signals, child processes           │
└───────────────┴──────────────────────────────────────────┘
                 Operating system (epoll / kqueue / IOCP)
  • Single-threaded for your JavaScript: only one callback runs at a time — no locks needed for shared variables.
  • Non-blocking I/O: waiting for the network/disk doesn't block the thread; Node continues with other work.
  • Great for I/O-bound work (APIs, proxies, real-time). CPU-bound work (image processing, big JSON parsing, heavy loops) blocks the event loop for everyone — move it to worker threads, a separate service, or a queue.
js
// Blocking vs non-blocking
const fs = require('node:fs');
const data = fs.readFileSync('big.log');          // ❌ blocks the event loop until the file is read
fs.readFile('big.log', (err, d) => { /* … */ });  // ✅ callback when done; loop keeps serving requests
const text = await fs.promises.readFile('big.log', 'utf8');   // ✅ promise version