Skip to content

Instantly share code, notes, and snippets.

@benjamingr
Created January 23, 2022 22:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjamingr/b1ad4d1a345b9f154cddf9c37769fbc1 to your computer and use it in GitHub Desktop.
Save benjamingr/b1ad4d1a345b9f154cddf9c37769fbc1 to your computer and use it in GitHub Desktop.
import { Readable, Transform, compose } from "stream";
{
// Before
const stream = new (class extends Readable {
constructor() {
super({ objectMode: true });
this.data = [1, 2, 3];
}
_read() {
this.push(this.data.shift() ?? null);
}
})();
const mapped = stream.pipe(new class extends Transform {
constructor() {
super({ objectMode: true });
}
_transform(chunk, encoding, callback) {
callback(null, chunk * 2);
}
}());
// Real world usage should typically prefer listening to `readable` and
// calling read
mapped.on("data", (data) => {
console.log(data);
});
}
{
// Interim #1
let data = [1, 2, 3];
const stream = new Readable({
objectMode: true,
read() {
this.push(data.shift() ?? null);
},
});
const mapped = stream.pipe(new Transform({
objectMode: true,
transform(chunk, encoding, callback) {
callback(null, chunk * 2);
},
}));
mapped.on("data", (data) => {
console.log(data);
});
}
{
// Interim #2 (modern)
(async () => {
const mapped = compose([1, 2, 3], async function* (input) {
for await(const item of input) yield item * 2;
});
for await (const data of mapped) {
console.log(data);
}
})();
}
{
// After
(async () => {
for await (const data of Readable.from([1, 2, 3]).map((x) => x * 2)) {
console.log(data);
}
})();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment