Transform streams

Topic 3 of 3 in Streams6 min readIntermediateFree course

Overview

Built-in transforms like createGzip() cover compression and encryption. But real data work needs custom steps: split text into lines, parse CSV rows, filter records, convert to another format, mask personal data. That’s what custom transform streams are for.

A transform sits in the middle of a pipeline. Chunks flow in, your code changes them, and new chunks flow out — while pipeline takes care of backpressure and errors.

Writing a transform

JavaScript
import { Transform } from 'node:stream';

const upperCase = new Transform({
  transform(chunk, encoding, callback) {
    callback(null, chunk.toString().toUpperCase());
  },
});

await pipeline(process.stdin, upperCase, process.stdout);
Terminal
echo "hello streams" | node upper.js   # HELLO STREAMS

The transform method is called once per chunk. When you’re done with the chunk, call callback(error, output):

  • callback(null, data) — push data out and ask for the next chunk.
  • callback() — push nothing for this chunk (useful for filtering).
  • callback(err) — fail the stream (and the whole pipeline).

To push several outputs for one input, call this.push(item) as many times as you need, then callback().

The chunk-boundary problem

Here’s the catch that trips up almost everyone. Chunks are cut at arbitrary byte positions — not at line breaks, not at commas, not even necessarily between characters.

Chunks of a CSV file arrive cut at random places: ‘id,name\n1,As’, ‘ha\n2,Ravi’, ‘\n3,Mi’, ‘na\n’. A transform appends each chunk to a buffer, emits every complete line and keeps the unfinished remainder, producing the lines ‘id,name’, ‘1,Asha’, ‘2,Ravi’ and ‘3,Mina’. flush() pushes out a last line with no trailing newline.

If you split each chunk on \n independently, a line cut in half becomes two broken lines. The fix: keep the incomplete end of each chunk and prepend it to the next one.

JavaScript
import { Transform } from 'node:stream';

export function splitLines() {
  let rest = '';
  return new Transform({
    readableObjectMode: true, // we push strings (lines), not byte chunks
    transform(chunk, encoding, callback) {
      const lines = (rest + chunk.toString('utf8')).split(/\r?\n/);
      rest = lines.pop();     // the last piece may be incomplete — keep it
      for (const line of lines) this.push(line);
      callback();
    },
    flush(callback) {
      if (rest) this.push(rest); // the final line, if the file didn't end with \n
      callback();
    },
  });
}

flush runs once, after the last chunk, so you can push out anything you were holding back.

Characters split across chunks

There’s a second, subtler problem: a multi-byte UTF-8 character (like é or an emoji) can be split across two chunks, so calling chunk.toString() on each half produces garbage. Two simple fixes:

  • Give the source an encoding — createReadStream(file, { encoding: 'utf8' }) — and Node handles the boundaries for you; or
  • Use a StringDecoder from node:string_decoder inside your transform.

Object mode

Normal streams carry bytes (Buffers or strings). In object mode, streams carry any JavaScript values — which is how you build data-processing pipelines:

JavaScript
const parseJsonLines = new Transform({
  writableObjectMode: true,   // receives lines (strings)
  readableObjectMode: true,   // pushes objects
  transform(line, encoding, callback) {
    try {
      callback(null, JSON.parse(line));
    } catch (err) {
      callback(new Error(`Bad JSON on a line: ${err.message}`));
    }
  },
});

Use objectMode: true to set both sides at once.

Generators: the simpler option

For many transforms, an async generator inside pipeline is shorter and easier to read than a Transform class:

JavaScript
await pipeline(
  createReadStream('events.ndjson', { encoding: 'utf8' }),
  splitLines(),
  async function* (lines) {
    for await (const line of lines) {
      const event = JSON.parse(line);
      if (event.type === 'purchase') {
        yield `${event.userId},${event.amount}\n`;
      }
    }
  },
  createWriteStream('purchases.csv'),
);

Use a generator for one-off steps. Write a reusable Transform (like splitLines) when the step is used in several places or needs fine control.

A realistic pipeline

Masking email addresses in a large log export before sharing it with a vendor:

JavaScript
const maskEmails = new Transform({
  objectMode: true,
  transform(line, _enc, callback) {
    callback(null, line.replace(/[\w.+-]+@[\w-]+\.[\w.]+/g, '***@***') + '\n');
  },
});

await pipeline(
  createReadStream('app.log', { encoding: 'utf8' }),
  splitLines(),
  maskEmails,
  createGzip(),
  createWriteStream('app-masked.log.gz'),
);

Four steps, any file size, constant memory, and a single try…catch for every possible failure.

Libraries

For common formats, use well-tested parsers rather than writing your own — CSV in particular has tricky rules about quotes and commas inside values. Packages such as csv-parse and csv-stringify provide transform streams that plug straight into pipeline.

The pattern to remember: buffer what’s incomplete, emit what’s complete, and flush what’s left at the end.

Exercise

CSV to NDJSON

Build a pipeline that reads users.csv (header row id,name,email), turns each data row into a JSON object, and writes one JSON object per line to users.ndjson. Use a line-splitting transform followed by an async generator.

JavaScript
import { createReadStream, createWriteStream } from 'node:fs';
import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';

Summary

  • A Transform stream receives chunks, changes them and pushes results out.
  • Implement transform(chunk, encoding, callback) and optionally flush(callback).
  • Chunks are cut at arbitrary byte positions — buffer partial lines and characters.
  • Object mode lets streams carry JavaScript objects instead of bytes.
  • For simple steps, an async generator inside pipeline is often clearer than a class.