Skip to content

Instantly share code, notes, and snippets.

@hoehrmann
Created April 19, 2019 22:21
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 hoehrmann/2d1c57f8664af8e7a76157d933caec2c to your computer and use it in GitHub Desktop.
Save hoehrmann/2d1c57f8664af8e7a76157d933caec2c to your computer and use it in GitHub Desktop.
NodeJS backpressure streams with prioritisation
const through2 = require('through2');
const split2 = require('split2');
var vowels = through2({ objectMode: true });
var consonants = through2({ objectMode: true });
var muxed = through2({ objectMode: true, highWaterMark: 1 });
[vowels, consonants].forEach(x => x.pipe(muxed));
muxed.pipe(process.stderr);
function demux(chunk, encoding, callback) {
if (/^[aeiuo]/.test(chunk)) {
vowels.push(chunk);
vowels.resume();
} else {
consonants.push(chunk);
}
callback();
}
const x = process.stdin
.pipe(split2(y => y))
.pipe(through2({ objectMode: true }, demux));
// for x in a i b c d e i f g h i j k l; do echo "$x"; done | node ....
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment