Skip to content

Instantly share code, notes, and snippets.

@glenjamin
Created November 6, 2013 08:37
Show Gist options
  • Save glenjamin/7332816 to your computer and use it in GitHub Desktop.
Save glenjamin/7332816 to your computer and use it in GitHub Desktop.
What's the "fast" way to read all the data from a socket?
// Basically every data read ever looks something like this
// Can this be optimised using the callback advice from http://blog.trevnorris.com/2013/08/long-live-callbacks.html
function getData(callback) {
http.get('http://localhost/whatever', function(err, res) {
if (err) return callback(err);
res.on('error', callback);
var buffers = [], length = 0;
res.on('data', function(chunk) {
buffers.push(chunk);
length += chunk.byteLength;
})
res.on('end', function() {
callback(null, Buffer.concat(buffers, length));
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment