Skip to content

Instantly share code, notes, and snippets.

@magicianShiro
Created July 1, 2017 04:33
Show Gist options
  • Save magicianShiro/d1b5c4423b01545419fcaa160a086e78 to your computer and use it in GitHub Desktop.
Save magicianShiro/d1b5c4423b01545419fcaa160a086e78 to your computer and use it in GitHub Desktop.
拼接buffer
var chunks = [];
var size = 0;
res.on('data', function (chunk) {
chunks.push(chunk);
size += chunk.length;
});
res.on('end', function () {
var data = null;
switch(chunks.length) {
case 0: data = new Buffer(0);
break;
case 1: data = chunks[0];
break;
default:
data = new Buffer(size);
for (var i = 0, pos = 0, l = chunks.length; i < l; i++) {
var chunk = chunks[i];
chunk.copy(data, pos);
pos += chunk.length;
}
break;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment