How to Load and save image using node.js?

A have this code:

var http = require('http');
var fs = require('fs');
var data;
var options = {
  host: 'nodejs.org',
  port: 80,
  path: '/images/logo.png',
  method: 'GET'
};
var req = http.request(options, function(res) {
  res.on('data', function (chunk) {
    data += chunk;
  });
  res.on('end', function () {
    fs.writeFile('1.png', data, function (err) {
      if(err) 
        console.log('NNOOOOOOOOOOOO');
    });
  });
});
req.on('error', function(e) {
  console.log('error: ' + e.message);
});
req.end();

This script create file 1.png and save got data but I can't open it in Windows.

Please, help.

You can do this :

var req = http.request(options, function(res) {
  var file = fs.createWriteStream('1.png');
  res.pipe(file);
});
req.on('error', function(e) {
  console.log('error: ' + e.message);
});
req.end();

Update

I checked your code and found two things :

  1. The data is not properly initialised.
  2. Use setEncoding to treat response as binary. Don't need to specify encoding in writeFile

So just add these two lines in beginning of http.request callback :

  res.setEncoding("binary") ;
  var data='';

Then your code should work fine.

You need to set the proper encoding.

res.setEncoding('binary')


fs.writeFile('1.png', data, {encoding: 'binary'}, function(err){