Skip to content

Instantly share code, notes, and snippets.

@nanha
Created March 13, 2013 03:56
Show Gist options
  • Save nanha/5149276 to your computer and use it in GitHub Desktop.
Save nanha/5149276 to your computer and use it in GitHub Desktop.
Awesome module split (https://github.com/dominictarr/split/blob/master/index.js) Customize for Nodes.js v0.10 Use StreamV2, duplex
/**
* https://github.com/dominictarr/split
* Customize for Node.js v0.10
*
* - remove through module
https://github.com/dominictarr/through/blob/master/index.js
* - use stream.Duplex (StreamV2)
*
* @author nanhapark
* @twitter @nanhapark
* @hompage http://nodeqa.com
*/
var stream = require('stream'), fs = require('fs');
function split() {
var soFar = '', matcher = '\n';
var dest = new stream.Duplex();
dest._read = function(size) {};
dest._write = function(chunk, encoding, cb) {
var pieces = (soFar + chunk).split(matcher);
soFar = pieces.pop();
for (var i = 0; i < pieces.length; i++) {
var piece = pieces[i];
this.push(piece);
}
cb();
};
dest.end = function() {
if (soFar)
this.push(soFar);
};
return dest;
}
fs.createReadStream(__filename)
.pipe(split())
.on('data', function (line) {
console.log(line.toString());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment