Streams are one of Node.js's most powerful abstractions. They let you process data piece by piece instead of loading everything into memory. There are four types: Readable, Writable, Duplex (both), and Transform (modifies data as it passes through).
Node.js
Beginner
11 min read
Readable and Writable Streams
Example
const { Readable, Writable, Transform } = require('stream');
// --- Custom Readable stream ---
class NumberStream extends Readable {
constructor(max) {
super({ objectMode: true });
this.current = 1;
this.max = max;
}
_read() {
if (this.current <= this.max) {
this.push(this.current++);
} else {
this.push(null); // Signal end of stream
}
}
}
// --- Custom Transform stream ---
class SquareTransform extends Transform {
constructor() {
super({ objectMode: true });
}
_transform(chunk, encoding, callback) {
this.push(chunk * chunk);
callback();
}
}
// --- Custom Writable stream ---
class SumWritable extends Writable {
constructor() {
super({ objectMode: true });
this.sum = 0;
}
_write(chunk, encoding, callback) {
this.sum += chunk;
callback();
}
}
// Pipe them together:
const numbers = new NumberStream(5); // 1 2 3 4 5
const squares = new SquareTransform(); // 1 4 9 16 25
const sum = new SumWritable(); // 55
numbers.pipe(squares).pipe(sum);
sum.on('finish', () => {
console.log('Sum of squares:', sum.sum); // 55
});