Last active
September 13, 2022 16:17
-
-
Save gagan-bansal/fd9df0fe00dfd2610e792a1b8f3be718 to your computer and use it in GitHub Desktop.
Node.js split stream in two streams.
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
// source code from https://stackoverflow.com/a/19561718/713573 | |
const fs = require("fs"); | |
const {Transform} = require('stream'); | |
const split = require('split'); | |
const readStream = fs.createReadStream('./numbers'); | |
const evenWriteStream = fs.createWriteStream('./evens'); | |
const oddWriteStream = fs.createWriteStream('./odds'); | |
class Even extends Transform { | |
_transform(chunk, encoding, cb) { | |
setTimeout(() => { | |
const val = parseInt(chunk.toString()); | |
if (val % 2 === 0) cb(null, val.toString() + '\n'); | |
else cb(); | |
}, Math.random() * 10); | |
} | |
} | |
class Odd extends Transform { | |
_transform(chunk, encoding, cb) { | |
setTimeout(() => { | |
const val = parseInt(chunk.toString()); | |
if (val % 2 !== 0) cb(null, val.toString() + '\n'); | |
else cb(); | |
}, Math.random() * 10); | |
} | |
} | |
const even = new Even(); | |
const odd = new Odd(); | |
readStream.pipe(split()).pipe(even).pipe(evenWriteStream); | |
readStream.pipe(split()).pipe(odd).pipe(oddWriteStream); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment