AceDevHub
Advanced Node.js Interview QuestionsAdvancedCode Output

Node.js · Question 88

What happens in this stream backpressure example?

Direct answer

Output: start, chunk: a, chunk: b, end, done — pipe connects readable to writable; chunks flow asynchronously after sync code; 'done' logs last because end fires after stream finishes (Q53).

Tracing pipe + data events shows when sync code runs vs when stream callbacks schedule on the event loop.

stream-trace.mjs
import { Readable, Writable } from "node:stream";

const readable = Readable.from(["a", "b"]);

const writable = new Writable({
  write(chunk, _enc, cb) {
    console.log("chunk:", chunk.toString());
    cb();
  },
});

console.log("start");

readable.pipe(writable);

readable.on("end", () => console.log("end"));
writable.on("finish", () => console.log("done"));

console.log("sync after pipe");
Output
start
sync after pipe
chunk: a
chunk: b
end
done
  • Sync first — start and sync after pipe before any chunk.
  • Chunks async — write callbacks run on subsequent ticks.
  • finish vs end — readable end then writable finish after all writes complete.