Lab 12: Streams & Buffers
Overview
Step 1: Readable Streams
const { Readable } = require('node:stream');
// Create from iterable
const fromArray = Readable.from([1, 2, 3, 4, 5]);
fromArray.on('data', chunk => process.stdout.write(String(chunk) + ' '));
fromArray.on('end', () => console.log('(end)'));
// Create custom Readable
class NumberStream extends Readable {
constructor(start, end, options) {
super({ ...options, objectMode: true });
this.current = start;
this.end = end;
}
_read() {
if (this.current <= this.end) {
this.push(this.current++);
} else {
this.push(null); // Signal end
}
}
}
const nums = new NumberStream(1, 5);
(async () => {
for await (const n of nums) {
process.stdout.write(n + ' ');
}
console.log();
})();
// Consuming with async iteration (recommended modern approach)
async function readAll(stream) {
const chunks = [];
for await (const chunk of stream) chunks.push(chunk);
return chunks;
}Step 2: Writable Streams
Step 3: Transform Streams
Step 4: Duplex Streams
Step 5: Pipeline
Step 6: Buffer Deep Dive
Step 7: Backpressure and highWaterMark
Step 8: Capstone — Stream Pipeline
Summary
Stream Type
Direction
Use Case
Buffer Method
Description
Last updated
