Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
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 });
Result
Open