Transform streams
Local practice: Node.js 22.16.0 on Linux x64; proposed 26.13.1 baseline remains untested. Save each example separately as main.mjs in a disposable directory. No packages or external services required. HTTP examples bind only to loopback and shut down after a finite scenario. Static Node.js code, not verified ByteMind execution.
Uppercase complete synthetic lines
import { Readable, Writable, Transform } from 'node:stream';import { pipeline, finished } from 'node:stream/promises';const upper = new Transform({transform(chunk, enc, done) { done(null, chunk.toString('utf8').toUpperCase()); }});let result = '';await pipeline(Readable.from(['pen\n','book\n']), upper, new Writable({write(c,e,cb){result += c.toString(); cb();}}));console.log(result.trim());Run:
node main.mjsExpected stdout:
PENBOOKExit status: 0. Expected stderr: empty.
How it works
Implement transform(chunk, encoding, callback) to process one input. Calling callback(null, value) completes that input and emits a result. Calling callback(error) reports failure. A transform may buffer partial records and emit later. The first example operates on complete synthetic lines; the second handles already parsed numbers. For arbitrary UTF-8 bytes use a decoder and a record parser rather than assuming lines arrive intact.
Transform numeric objects
import { Readable, Writable, Transform } from 'node:stream';import { pipeline, finished } from 'node:stream/promises';const double = new Transform({objectMode:true, transform(n,e,done){done(null,n*2);}});const result = [];await pipeline(Readable.from([3,5]), double, new Writable({objectMode:true,write(n,e,done){result.push(n);done();}}));console.log(JSON.stringify(result));Run:
node main.mjsExpected stdout:
[6,10]Exit status: 0. Expected stderr: empty.
Common mistake
Never call the completion callback twice, or omit it on a branch. Treating every input buffer as a full line breaks split records.
Practice
Change the object transform to return the square of each number. Explain why objectMode is needed for numeric values.
Further reading: Authoritative source 1. Internal reference routes remain proposed until repository discovery.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Transform streams — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
Which stream has both readable and writable sides and transforms data?
What does callback(null, value) do in transform()?
What must a transform do with a partial UTF-8 character?