Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing image to local server

Update

The accepted answer was good for last year but today I would use the package everyone else uses: https://github.com/mikeal/request


Original

I'm trying to grab google's logo and save it to my server with node.js.

This is what I have right now and doesn't work:

        var options = {             host: 'google.com',             port: 80,             path: '/images/logos/ps_logo2.png'         };          var request = http.get(options);          request.on('response', function (res) {             res.on('data', function (chunk) {                 fs.writeFile(dir+'image.png', chunk, function (err) {                     if (err) throw err;                     console.log('It\'s saved!');                 });             });         }); 

How can I get this working?

like image 603
Mark Avatar asked Mar 14 '11 03:03

Mark


People also ask

How do I write an image in node JS?

To write an image to a local server with Node. js, we can use the fs. writeFile method. to call res.


1 Answers

A few things happening here:

  1. I assume you required fs/http, and set the dir variable :)
  2. google.com redirects to www.google.com, so you're saving the redirect response's body, not the image
  3. the response is streamed. that means the 'data' event fires many times, not once. you have to save and join all the chunks together to get the full response body
  4. since you're getting binary data, you have to set the encoding accordingly on response and writeFile (default is utf8)

This should work:

var http = require('http')   , fs = require('fs')   , options  options = {     host: 'www.google.com'   , port: 80   , path: '/images/logos/ps_logo2.png' }  var request = http.get(options, function(res){     var imagedata = ''     res.setEncoding('binary')      res.on('data', function(chunk){         imagedata += chunk     })      res.on('end', function(){         fs.writeFile('logo.png', imagedata, 'binary', function(err){             if (err) throw err             console.log('File saved.')         })     })  }) 
like image 131
Ricardo Tomasi Avatar answered Sep 21 '22 06:09

Ricardo Tomasi