Readable Stream Helpers Chain Filter, Map, and Take
Transform Node Readable streams lazily with built-in filter, map, take, and toArray helpers so consumers pull only the records they need.
Code
import { Readable } from 'node:stream';
let produced = 0;
async function* generateJobs() {
for (let id = 1; id <= 100; id++) {
produced++;
yield { id, ok: id % 2 === 0, ms: id * 15 };
}
}
const selected = await Readable.from(generateJobs())
.filter((job) => job.ok && job.ms >= 60)
.map((job) => `job-${job.id}:${job.ms}ms`)
.take(3)
.toArray();
console.log('selected:', JSON.stringify(selected));
// Upstream generator stops well before producing all 100 jobs once take(3) completes
console.log('upstream jobs produced:', produced, 'of 100');Output
Captured from a sandboxed run of this snippet in the build pipeline.
selected: ["job-4:60ms","job-6:90ms","job-8:120ms"]
upstream jobs produced: 16 of 100Implementation trace — Readable Stream Helpers Chain Filter, Map, and Take
Iteration happens inside for (let id = 1; id <= 100; id++) — everything outside it runs once. The async parts await their results, which keeps ordering predictable. node:stream supplies Readable — built-in surface, no package involved.
Demo state sits in top-level bindings: produced, selected.
What to watch for
node:streamresolves inside Node.js without any package — it is a core module.
Putting it to use
The demo output is labeled (selected:, upstream jobs produced:); each label names the call that printed it.
Core lines
yield { id, ok: id % 2 === 0, ms: id * 15 };
.map((job) => `job-${job.id}:${job.ms}ms`)
.take(3)
.toArray();
FAQ
- What does this import from outside the project?
- Only `node:stream`, and that is a Node.js built-in — it comes with the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.