Skip to content

Instantly share code, notes, and snippets.

@heapwolf
Created August 6, 2012 16:14
Show Gist options
  • Save heapwolf/3276019 to your computer and use it in GitHub Desktop.
Save heapwolf/3276019 to your computer and use it in GitHub Desktop.
emitters/http
var req = http.request(options);
req.on('response', function(response) {
response.on("data", function(data) {
console.log("some data from the response", data);
});
response.on("end", function() {
console.log("response ended");
});
});
req.on('error', function(err) {
console.error('request error:', err);
});
req.end();
@occasl
Copy link

occasl commented Aug 24, 2012

Suppose you have a long data stream that comes back from a REST service response. Is the best thing to do is collect the chunked data on the data emitter and then do something with that chunk on the end emmitter, say as follows:

var fourSquareGet = {
    host: 'api.foursquare.com',
    port: 443,
    path: '/v2/venues/search?ll=33.88,-119.19&query=burger*',
    method: 'GET'
};
setInterval(function () {
    var reqGet = https.request(fourSquareGet, function (res) {
        var content;

        res.on('data', function (chunk) {
            content += chunk;
        });
        res.on('end', function () {
            // remove 'undefined that appears before JSON for some reason
            content = JSON.parse(content.substring(9, content.length));
            db.checkins.save(content.response.venues, function (err, saved) {
                if (err || !saved) throw err;
            });
            console.info("\nSaved from Foursquare\n");
        });
    });

    reqGet.end();
    reqGet.on('error', function (e) {
        console.error(e);
    });
}, 25000);

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