Created
March 5, 2023 01:32
-
-
Save EnzoPortela/9625459d84d6a010e4f2954f8240b288 to your computer and use it in GitHub Desktop.
Streams in Node.js - Simple demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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