BugCast
Node Node.js

Node.js Event Loop & Streams

How Node differs from browser JS, and why streams matter in backend interviews.

BugCast Admin··8 min read

Node.js Event Loop Phases

  1. Timers — setTimeout, setInterval
  2. Pending callbacks — I/O callbacks
  3. Idle, prepare — internal
  4. Poll — fetch new I/O events
  5. Check — setImmediate
  6. 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().

#nodejs#streams#interview

Related posts