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

Updated 28 Nov 20265 min read
Streams in Node.js: Read, Transform and Pipe Data with Examples

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

Readable

Supplies data to the program

fs.createReadStream()

Writable

Receives data from the program

fs.createWriteStream()

Duplex

Supports both directions

Network socket

Transform

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:

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:

Code
id,item,total
101,pen,30
102,book,80
103,bag,750

The 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.

Three-stage pipeline: orders.csv split into six 12-byte chunks, a Transform computing totals 30, 80 and 750, then the four-line totals.csv.

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:

js
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.

Timeline of an 8-byte write buffer: AAAA returns true, BBBB fills it and returns false, two 20 ms writes drain it, then CCCC returns true.

Error handling, completion, and common stream mistakes

Problem

Consequence

Fix

Treat each chunk as one record

IDs 101 and 102 break

Keep a carry buffer

Chain pipe() calls without coordinated rejection

Multi-stage cleanup becomes harder

Await pipeline()

Ignore write() returning false

Buffered data can keep growing

Pause for drain

Call write() after end()

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:

  1. Given the first three 12-byte chunks, which lines can be transformed? The header after chunk 2 and order 101 after chunk 3. The respective carries 10 and 1 are incomplete.

  2. Classify file input, output file, a socket, and the calculator. They are Readable, Writable, Duplex, and Transform. Justify each answer using data direction.

  3. Why does BBBB returning false matter? The producer waits for drain before sending CCCC, preventing unbounded queue growth.

  4. What if the last line has no final newline? flush() still emits the 750 row.

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.