Full answer
A Transform has a writable side (input) and a readable side (output). You provide two methods:
- transform(chunk, encoding, callback): called for each input chunk. Call this.push(output) zero or more times, then callback(). callback(err) fails the stream. callback(null, data) is a shortcut for one push.
- flush(callback): called once after the last chunk and before 'end'. Emit leftovers here.
Why partial chunks matter: a file stream or a socket splits data at arbitrary byte positions, not at line ends. One line can arrive in two chunks, and one chunk can hold several lines. A line splitter therefore keeps a string buffer of the unfinished tail.
Details that cause bugs:
- Multi-byte characters can be cut by a chunk boundary. Use StringDecoder (or set decodeStrings and encoding correctly) so you do not decode half a character.
- Always call the callback exactly once for each transform call, and also on error paths.
- Use readableObjectMode: true when the output is lines or objects and not Buffers.
- Respect backpressure: push returns false when the readable buffer is full. Inside transform you can usually ignore it, because the stream stops calling transform until it drains.
- Keep CPU work small per chunk, or move it to a worker.
For short stages, an async generator function in pipeline does the same with less ceremony, but a class is easier to unit test and reuse.
const { Transform, Readable } = require('node:stream');
const { StringDecoder } = require('node:string_decoder');
const { pipeline } = require('node:stream/promises');
class LineSplitter extends Transform {
constructor({ withFlush = true } = {}) {
super({ readableObjectMode: true });
this.decoder = new StringDecoder('utf8');
this.tail = '';
this.withFlush = withFlush;
}
_transform(chunk, encoding, callback) {
const text = this.tail + this.decoder.write(chunk);
const lines = text.split('\n');
this.tail = lines.pop(); // the last piece may be incomplete
for (const line of lines) this.push(line);
callback();
}
_flush(callback) {
if (this.withFlush) {
const rest = this.tail + this.decoder.end();
if (rest) this.push(rest);
}
callback();
}
}
async function collect(withFlush) {
// Chunk boundaries cut a line, and a 2-byte character (é) is split across chunks.
const euro = Buffer.from('caf\u00e9\nlast');
const chunks = [Buffer.from('one\ntw'), Buffer.from('o\nthree\n'), euro.subarray(0, 4), euro.subarray(4)];
const lines = [];
await pipeline(
Readable.from(chunks, { objectMode: false }),
new LineSplitter({ withFlush }),
async function (source) { for await (const line of source) lines.push(line); },
);
return lines;
}
async function main() {
console.log('with flush :', JSON.stringify(await collect(true)));
console.log('without flush:', JSON.stringify(await collect(false)));
}
main();The input chunks cut a line and a character in the middle. Without flush the last line is lost. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): with flush : ["one","two","three","café","last"] without flush: ["one","two","three","café"]
Key points
- transform() receives chunks, pushes results and calls the callback.
- Chunks split data anywhere, so keep the incomplete tail.
- flush() emits what remains at the end of input.
- Use StringDecoder for multi-byte text.
- Call the callback exactly once per chunk.
Common mistakes
- Splitting each chunk on newlines without keeping the tail.
- Decoding each chunk with toString() and breaking multi-byte characters.
- Skipping flush and losing the last line when the file has no final newline.
- Calling the callback twice, or not at all on an error path.
- Forgetting readableObjectMode when pushing strings you want to keep as separate items.
Follow-ups
- How would you handle Windows line endings (\r\n)?
- How would you limit the maximum line length to protect memory?
- When is an async generator stage better than a Transform class?
Tips
- Show the tail buffer idea in one sentence.
- Mention flush before the code.
- Mention StringDecoder to show you know about multi-byte text.