Skip to content

Instantly share code, notes, and snippets.

@andrewvc
Created April 30, 2010 03:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewvc/384706 to your computer and use it in GitHub Desktop.
Save andrewvc/384706 to your computer and use it in GitHub Desktop.
//Simple (slow) way to transfer binary data
fs.createReadStream(filepath,{'flags': 'r', 'encoding':
'binary', 'mode': 0666, 'bufferSize': 64 * 1024})
.addListener("data", function(chunk){
res.write(chunk, 'binary');
})
.addListener("close",function() {
res.close();
})
//Faster way to transfer binary data
var chunkSize = 64 * 1024;
var bufSize = 64 * 1024;
var bufPos = 0;
var buf = new Buffer(bufSize);
fs.createReadStream(filepath,{'flags': 'r', 'encoding':
'binary', 'mode': 0666, 'bufferSize': chunkSize})
.addListener("data", function(chunk){
//Since this is binary data, we cat use String.prototype.length
//We *WANT* the number of chars, since node uses UTF-16 for bin data
//meaning one byte bin data = one char = two bytes.
var bufNextPos = bufPos + chunk.length;
if (bufNextPos == bufSize) {
buf.write(chunk,'binary',bufPos);
res.write(buf);
bufPos = 0;
}
else {
buf.write(chunk,'binary',bufPos);
bufPos = bufNextPos;
}
})
.addListener("close",function() {
if (bufPos != 0) {
res.write(buf.slice(0,bufPos));
res.end();
}
else
res.close();
})
@balupton
Copy link

What is res?

@andrewvc
Copy link
Author

Hmmm, I forgot now, this was posted ages ago. I believe it was either a stream or the HTTP response.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment