Skip to content

Instantly share code, notes, and snippets.

@gagan-bansal
Last active September 13, 2022 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gagan-bansal/fd9df0fe00dfd2610e792a1b8f3be718 to your computer and use it in GitHub Desktop.
Save gagan-bansal/fd9df0fe00dfd2610e792a1b8f3be718 to your computer and use it in GitHub Desktop.
Node.js split stream in two streams.
// 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