Skip to content

Instantly share code, notes, and snippets.

@heapwolf heapwolf/15.js
Created Aug 6, 2012

Embed
What would you like to do?
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

This comment has been minimized.

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
You can’t perform that action at this time.