Streams in Node.js: Read, Transform and Pipe Data with Examples
Build and trace a Node.js pipeline that reads CSV data in small chunks, preserves split rows, calculates totals, handles backpressure, and reports failures.
KnowledgeGate Team
Exam prep & CS education

readFile() feels simple until the input is large, arrives over a network, or must be transformed while it is still arriving. The useful mental model is that data moves through a stream in chunks, and each stage consumes only what it can handle. The example reads a 63-byte orders.csv file in 12-byte chunks, calculates three row totals, and writes totals.csv without mistaking a chunk for a CSV row. The Coding and Skill Development Courses connects this example to related programming topics.
What a Node.js stream is and when it helps
A stream is an interface for moving data incrementally between a source and a destination. await readFile("orders.csv") resolves after the whole 63-byte tutorial file is available. createReadStream(..., { highWaterMark: 12 }) exposes successive chunks while reading continues. Streaming controls buffering and can overlap processing with input, but it does not guarantee that every job becomes faster.
The same idea applies to a file upload arriving through an HTTP request, a 400 MB log file read from disk, or rows being written to a compressed backup. The small input makes every byte and row easy to check. Request and response streams also fit into the wider Web Technologies for Teaching Exams of a web application.
Readable, Writable, Duplex and Transform streams
The Node.js Stream documentation defines four stream types that matter here:
Type | Direction from the program's view | Example |
|---|---|---|
| Supplies data to the program |
|
| Receives data from the program |
|
| Supports both directions | Network socket |
| Produces output derived from its input | CSV total calculator |
A pipe connects readable output to writable input. On the readable side, end means no more data remains. On the writable side, finish occurs after end() has been called and all data has been processed. close concerns resource closure, while error signals failure. Do not assume one universal close ordering across every stream implementation.
Runnable example: turn three CSV orders into totals
Save this exact CommonJS program as streams-demo.js:
const { createReadStream, createWriteStream } = require("node:fs");
const { writeFile, readFile } = require("node:fs/promises");
const { Transform } = require("node:stream");
const { pipeline } = require("node:stream/promises");
async function main() {
const input =
"id,item,qty,unitPrice\n" +
"101,pen,2,15\n" +
"102,book,1,80\n" +
"103,bag,3,250\n";
await writeFile("orders.csv", input);
let carry = "";
function convertLine(line) {
const [id, item, qty, unitPrice] = line.split(",");
if (id === "id") return "id,item,total\n";
return `${id},${item},${Number(qty) * Number(unitPrice)}\n`;
}
const addTotal = new Transform({
decodeStrings: false,
transform(chunk, _encoding, callback) {
console.log("chunk:", JSON.stringify(chunk));
carry += chunk;
const lines = carry.split("\n");
carry = lines.pop();
for (const line of lines) {
if (line) this.push(convertLine(line));
}
callback();
},
flush(callback) {
if (carry) this.push(convertLine(carry));
callback();
},
});
await pipeline(
createReadStream("orders.csv", {
encoding: "utf8",
highWaterMark: 12,
}),
addTotal,
createWriteStream("totals.csv")
);
console.log("output:\n" + await readFile("totals.csv", "utf8"));
}
main().catch(console.error);Run node streams-demo.js. Order 101 gives 2 x 15 = 30, order 102 gives 1 x 80 = 80, and order 103 gives 3 x 250 = 750. The output is:
id,item,total
101,pen,30
102,book,80
103,bag,750The Readable supplies text. The Transform keeps incomplete lines and pushes converted lines. The Writable persists them. The awaited pipeline() settles after the chain completes, or rejects if any stage fails. The Node.js, Express.js & MongoDB course places this stream work inside the surrounding backend sequence.
A chunk is not a row: trace the exact 12-byte boundaries
The six logged chunks are "id,item,qty,", "unitPrice\n10", "1,pen,2,15\n1", "02,book,1,80", "\n103,bag,3,2", and "50\n". Thus 101 arrives as 10 plus 1, 102 as 1 plus 02, and 250 as 2 plus 50.
After chunk 1, carry is id,item,qty,. Chunk 2 completes the header and leaves 10. Chunk 3 completes order 101 and leaves 1. Chunk 4 extends that carry to the still-incomplete order 102. Chunk 5 completes order 102 and leaves 103,bag,3,2. Chunk 6 completes order 103; its final newline leaves an empty carry. flush() still emits a final row when an input has no trailing newline. This hand-written parser suits controlled data, not quoted commas or malformed numeric fields.

Backpressure keeps a fast producer from overrunning a slow consumer
As the Node.js documentation specifies, writable.write(chunk) returning true means the producer may continue for now. false means it should pause and wait for drain. A highWaterMark is a buffering threshold, not a promise that every chunk has that exact size or that memory can never exceed it.
The writable sink uses an 8-byte threshold and a 20 ms delay per write:
const { once } = require("node:events");
const { Writable } = require("node:stream");
(async () => {
const sink = new Writable({
highWaterMark: 8,
write(_chunk, _encoding, callback) {
setTimeout(callback, 20);
},
});
for (const text of ["AAAA", "BBBB", "CCCC"]) {
const ready = sink.write(text);
console.log(`${text}: ready=${ready}, buffered=${sink.writableLength}`);
if (!ready) {
await once(sink, "drain");
console.log(`drain: buffered=${sink.writableLength}`);
}
}
sink.end();
await once(sink, "finish");
console.log("finish");
})();Its trace is AAAA: ready=true, buffered=4; BBBB: ready=false, buffered=8; drain: buffered=0; CCCC: ready=true, buffered=4; finish. pipe() and pipeline() coordinate this pause and resume pressure automatically for ordinary chains.

Error handling, completion, and common stream mistakes
Problem | Consequence | Fix |
|---|---|---|
Treat each chunk as one record | IDs | Keep a carry buffer |
Chain | Multi-stage cleanup becomes harder | Await |
Ignore | Buffered data can keep growing | Pause for |
Call | The lifecycle is violated | Finish writes before ending |
In the CSV chain, the source's readable side reaches end after "50\n". The destination reaches finish only after the four output lines have been accepted and flushed. A source end does not prove that the destination file is complete.
As a failure exercise, make convertLine() reject any row where qty or unitPrice is not a finite, non-negative number. Call callback(new Error("Invalid order 102")) from the transform when validation fails. If order 102 becomes 102,book,-1,80, await pipeline(...) must reject with that message. Treat the run as failed. Production code should replace output only after successful validation, rather than promising that a partial file is useful.
How practice and interviews test streams
Use these four prompts to test chunk boundaries, stream types, backpressure, and end-of-input handling:
Given the first three 12-byte chunks, which lines can be transformed? The header after chunk 2 and order
101after chunk 3. The respective carries10and1are incomplete.Classify file input, output file, a socket, and the calculator. They are Readable, Writable, Duplex, and Transform. Justify each answer using data direction.
Why does
BBBBreturningfalsematter? The producer waits fordrainbefore sendingCCCC, preventing unbounded queue growth.What if the last line has no final newline?
flush()still emits the750row.
Short version and the next study step
Streams move chunks, chunk boundaries do not define records, pipeline() connects stages and surfaces failure, and backpressure tells a producer when to pause. Rerun the example with highWaterMark: 5 and predict why the four output lines stay unchanged even though the chunk trace changes. Next, read Mongoose Schemas and Models. Project-focused learners can continue with the MERN Stack Course, while Node.js learners can follow the Node.js, Express.js & MongoDB Course.
Keep learning
Node.js File System Tutorial: Read, Write and Manage Files with Runnable Examples
Build one path-safe Node.js lab that reads attempt records, calculates accuracy, creates an output directory, writes a JSON summary, and appends an audit log.
Node.js Interview Questions for Freshers: The Event Loop, Streams, Clustering and Express
Learn the Node.js concepts that expose real understanding: callback order, stream backpressure, multi-core scaling and Express middleware. Includes two exact traces.
Buffers in Node.js: A Practical Tutorial with Binary Data Examples
Learn how Node.js Buffers represent bytes, then practise safe allocation, encoding, binary field access, copying, concatenation, and boundary checks.
SQL with Node.js: Query PostgreSQL Safely with Runnable Examples
Build a small CommonJS command-line project that reads and writes PostgreSQL safely, then protects a two-table library loan with one transaction.





