Skip to content

Instantly share code, notes, and snippets.

@EnzoPortela
Created March 5, 2023 01:32
Show Gist options
  • Save EnzoPortela/9625459d84d6a010e4f2954f8240b288 to your computer and use it in GitHub Desktop.
Save EnzoPortela/9625459d84d6a010e4f2954f8240b288 to your computer and use it in GitHub Desktop.
Streams in Node.js - Simple demo
import { Readable, Writable, Transform } from "node:stream";
class OneToHundredStream extends Readable {
index = 1;
_read() {
const i = this.index++;
setTimeout(() => {
if (i > 100) {
this.push(null);
} else {
const buf = Buffer.from(String(i));
this.push(buf);
}
}, 1000);
}
}
class InvertNumberStream extends Transform {
_transform(chunk, encoding, callback) {
const transformed = Number(chunk.toString()) * -1;
callback(null, Buffer.from(String(transformed)));
}
}
class MultiplyByTenStream extends Writable {
_write(chunck, encoding, callback) {
console.log(Number(chunck.toString()) * 10);
callback();
}
}
new OneToHundredStream()
.pipe(new InvertNumberStream())
.pipe(new MultiplyByTenStream());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment