Transform streams
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
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);echo "hello streams" | node upper.js # HELLO STREAMSThe transform method is called once per chunk. When you’re done with the chunk, call callback(error, output):
callback(null, data)— pushdataout 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.
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.
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
StringDecoderfromnode:string_decoderinside 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:
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:
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:
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.
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.
import { createReadStream, createWriteStream } from 'node:fs';
import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';import { createReadStream, createWriteStream } from 'node:fs';
import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
function splitLines() {
let rest = '';
return new Transform({
readableObjectMode: true,
transform(chunk, encoding, callback) {
const lines = (rest + chunk.toString('utf8')).split(/\r?\n/);
rest = lines.pop();
for (const line of lines) if (line) this.push(line);
callback();
},
flush(callback) {
if (rest) this.push(rest);
callback();
},
});
}
await pipeline(
createReadStream('users.csv'),
splitLines(),
async function* (lines) {
let headers;
for await (const line of lines) {
const cells = line.split(',');
if (!headers) { headers = cells; continue; }
yield JSON.stringify(Object.fromEntries(headers.map((h, i) => [h, cells[i]]))) + '\n';
}
},
createWriteStream('users.ndjson'),
);Summary
- A Transform stream receives chunks, changes them and pushes results out.
- Implement
transform(chunk, encoding, callback)and optionallyflush(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
pipelineis often clearer than a class.