Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS: How to save facebook profile picture

I am using express and nodejs and am having problems saving facebook profile pictures to my server.

Location of picture: http://profile.ak.fbcdn.net/hprofile-ak-ash2/275619_223605264_963427746_n.jpg

Script Being Used:

    var http = require('http')
    var fs = require('fs')

    var options = {
      host: 'http://profile.ak.fbcdn.net',
      port: 80,
      path: '/hprofile-ak-ash2/275619_223605264_963427746_n.jpg'
    }

    var request = http.get(options, function(res){
      res.setEncoding('binary')

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

      res.on('end', function(){
        fs.writeFile('logo.jpg', imagedata, 'binary', function (err) {
          if(err){throw err}
          console.log('It\'s saved!');
        })
      })
    })

The image saves but is empty. Console logging the image data is blank too. I followed this example origionally which does work for me. Just changing the location of the image to the facebook pic breaks the script.

like image 459
wilsonpage Avatar asked Dec 22 '22 08:12

wilsonpage


1 Answers

I ended up coming up with a function that worked:

var http    = require('http');
var fs  = require('fs');
var url     = require('url');

var getImg = function(o, cb){
    var port    = o.port || 80,
        url     = url.parse(o.url);

    var options = {
      host: url.hostname,
      port: port,
      path: url.pathname
    };

    http.get(options, function(res) {
        console.log("Got response: " + res.statusCode);
        res.setEncoding('binary')
        var imagedata = ''
        res.on('data', function(chunk){
            imagedata+= chunk; 
        });
        res.on('end', function(){
            fs.writeFile(o.dest, imagedata, 'binary', cb);
        });
    }).on('error', function(e) {
        console.log("Got error: " + e.message);
    });
}

USAGE:

    getImg({
        url: "http://UrlToImage.com",
        dest: __dirname + '/your/path/to/save/imageName.jpg'
    },function(err){
        console.log('image saved!')
    })
like image 192
wilsonpage Avatar answered Dec 24 '22 01:12

wilsonpage