Skip to content

Instantly share code, notes, and snippets.

@klovadis
Created May 26, 2012 11:53
Show Gist options
  • Save klovadis/2793677 to your computer and use it in GitHub Desktop.
Save klovadis/2793677 to your computer and use it in GitHub Desktop.
Helper function to handle messages from a newline separated stream
// returns a function that spits out messages to a callback
// function; those messages have been split by newline
function newLineStream(callback) {
var buffer = '';
return (function (chunk) {
var i = 0, piece = '', offset = 0;
buffer += chunk;
while ( (i = buffer.indexOf('\n', offset)) !== -1) {
piece = buffer.substr(offset, i - offset);
offset = i + 1;
callback(piece);
}
buffer = buffer.substr(offset);
});
} // newLineStream
// example use
var myListener = newLineStream( function (message) {
console.log('Message:', message);
});
// add listener to "data" event
myStream.on('data', myListener);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment