Read a stream in nodejs
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
// use tail -f /file/to/watch | node process_stdio.js to consume a stream | |
var partial = "", queue = []; | |
stdio = process.stdio; | |
stdio.open(); | |
// Grab whole lines off of stdio | |
stdio.addListener("data", function(chunk) { | |
if (chunk) { | |
if ("" != partial) { | |
chunk = partial+chunk; | |
partial = ""; | |
} | |
var data = chunk.split("\n"); | |
if (!chunk.match(/\n$/)) { | |
partial += data.pop(); | |
} | |
queue = queue.concat(data.map(function(n){return n.replace(/(^\s+|\s+$)/, "");}).filter(function(n){return "" != n;})); | |
} | |
}); | |
// Process messages on queue every 100ms (probably can bring this down) | |
setInterval(function(){ | |
if (queue.length) { | |
var batch = queue.splice(0, 250); | |
} | |
}, 100); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment