jesse1981
5/7/2013 - 11:42 PM

Fetch Instagram images which contain specified tag.

Fetch Instagram images which contain specified tag.

var http = require("http"),
    url = require("url"),
    fs = require("fs"),
    async = require("async"),
    Instagram = require('instagram-node-lib');

Instagram.set('client_id', /* client key */);
Instagram.set('client_secret', /* client secret */);

fetchTag('cat', 400);

function fetchTag(tag, total) {
  var count = 0;
  var fetched = {};  // keep duplicates at bay
  var next_max_id = null;

  async.whilst(
    function () {
      return count < total;
    },
    function (done) {
      console.log("fetching photos for tag '" + tag + "'");

      var options = {
        name: tag,
        count: total,
        complete: function(data, pagination) {
          next_max_id = pagination.next_max_id;

          data.forEach(function(datum) {
            var uri = datum.images.low_resolution.url;
            if (!fetched[uri]) {
              count++;
              saveFile(count, uri);
              fetched[uri] = true;
            }
          });

          setTimeout(done, 10000);
        }
      }
      if (next_max_id) {
        options.next_max_id = next_max_id;
      }
      Instagram.tags.recent(options);
    }
  );
}

function saveFile(id, uri) {
  var options = url.parse(uri);

  http.get(options, function(res) {
    var imagedata = "";
    res.setEncoding('binary');

    res.on('data', function(chunk) {
      imagedata += chunk
    });

    res.on('end', function(){
      fs.writeFile("instagrams/" + id + '.jpg', imagedata, 'binary', function(err) {
        if (err) throw err;
        console.log("File " + id + " saved");
      })
    })
  })
}