Skip to content

Instantly share code, notes, and snippets.

@niklasfi
Created February 24, 2011 19:40
Show Gist options
  • Save niklasfi/842734 to your computer and use it in GitHub Desktop.
Save niklasfi/842734 to your computer and use it in GitHub Desktop.
Buffering
Server.prototype.file2res = function(path,call){
var start = call.start;
var remaining = call.end-call.start+1;
fs.open(path,'r',0666, function(err,fd){
if(err) throw err;
var b = new Buffer(1024*1024*10);
var onDrain = function(){
//console.log('rem: ' + remaining);
if (remaining)
fs.read(fd,b,0,Math.min(1024*1024,remaining),start,function(err,bytesRead){
if(err) throw err;
var part = b.slice(0,bytesRead);
start += bytesRead;
this.totalTraffic += bytesRead;
remaining -= bytesRead;
if(remaining && call.res.write(part)){
onDrain();
}
else if(!remaining)
call.res.end(part);
})
}
call.res.on('drain',onDrain);
onDrain();
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment