Node.js Event Loop Phases
- Timers — setTimeout, setInterval
- Pending callbacks — I/O callbacks
- Idle, prepare — internal
- Poll — fetch new I/O events
- Check — setImmediate
- Close callbacks — socket.on('close')
Streams
Process data chunk-by-chunk instead of loading everything into memory.
const fs = require("fs");
fs.createReadStream("large-file.csv")
.pipe(fs.createWriteStream("copy.csv"));
Stream types: Readable, Writable, Duplex, Transform.
Interview Questions
Q: Is Node.js single-threaded?
JavaScript runs on one thread, but libuv uses a thread pool for I/O, crypto, and file operations.
Q: setImmediate vs setTimeout(0)?
setImmediate runs in the check phase after poll. setTimeout(0) runs in timers phase. Order depends on context.
Q: Why use streams for large files?
Constant memory usage, backpressure handling, composable pipelines with .pipe().