Intermediate Node.js Interview QuestionsIntermediateConcept
Node.js · Question 51
How do Readable and Writable streams work in Node.js?
Direct answer
Readable emits 'data' chunks or is consumed via async iteration/read(); Writable accepts write() chunks and signals completion with end() — both pause when internal buffers exceed highWaterMark until the consumer catches up.
Readable streams produce data; Writable streams consume it. Modes matter: flowing mode auto-emits 'data'; paused mode uses read() explicitly.
| Readable | Writable |
|---|---|
| on('data', fn) / for await | write(chunk, cb) |
| on('end') when exhausted | end() / end(chunk) to finish |
| pause() / resume() | cork() / uncork() batch writes |
| pipe(writable) | Returns backpressure signal via write return false |
- Create readable — fs.createReadStream or Readable.from(array).
- Consume — pipeline to writable or collect with async iteration.
- Handle errors — 'error' event on both sides; destroy stream on failure.
readable-writable.mjs
import fs from "node:fs";
const readable = fs.createReadStream("large-export.ndjson", { encoding: "utf8" });
const writable = fs.createWriteStream("filtered.ndjson");
readable.on("data", (line) => {
if (line.includes("nodejs")) writable.write(line);
});
readable.on("end", () => writable.end());
readable.on("error", (err) => {
writable.destroy(err);
});
// Better: await pipeline(readable, transform, writable)