Created
June 24, 2011 00:01
-
-
Save gliese1337/1043936 to your computer and use it in GitHub Desktop.
Accumulate the output of a stream into a string.
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
/* | |
* No sentinel results in reading the entire stream until it ends, a | |
* numeric sentinel reads fixed length chunks, and a string sentinel | |
* reads chunks bounded by the sentinel string | |
*/ | |
exports.accumulate = function(stream,opts,callback){ | |
stream.pause(); | |
if(!callback){ | |
callback = opts; | |
opts = {encoding:'utf8'}; | |
} | |
stream.setEncoding(opts.encoding || 'utf8'); | |
switch(typeof opts.sentinel){ | |
case 'undefined': | |
case false: | |
default: dumpStream(stream,callback);break | |
case 'string': readSentinel(stream,opts.sentinel,callback);break | |
case 'number': readLength(stream,opts.sentinel,callback); | |
} | |
stream.resume(); | |
} | |
function dumpStream(stream,callback){ | |
var str=''; | |
stream.on('data',function(data){str+=data;}); | |
stream.on('end',function(){callback(str);}); | |
} | |
function readSentinel(stream,sentinel,callback){ | |
var str='',that=this,slen=sentinel.length; | |
stream.on('data',function(data){ | |
var i=0,j; | |
str += data; | |
while((j = str.indexOf(sentinel,i))!==-1){ | |
j+=slen; | |
callback(str.substring(i,j)); | |
i=j; | |
} | |
if(i){str = str.substr(i);} | |
}); | |
stream.on('end',function(){callback(str);}); | |
} | |
function readLength(stream,length,callback){ | |
var str=''; | |
stream.on('data',function(data){ | |
var i,j,end; | |
str += data; | |
end = str.length-length; | |
for(i=0;i<end;i+=length){ | |
callback(str.substr(i,length)); | |
} | |
if(i){str = str.substr(i);} | |
}); | |
stream.on('end',function(){callback(str);}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment