Created
November 6, 2013 08:37
-
-
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?
This file contains hidden or 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
// 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