2

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Sable Added the explanation
Just saying - after fixing the code with this solution - the file doesn't open because nodejs.org/images/logo.png returning "301 Moved Permanently" and saving the headers into the file.
1

You need to set the proper encoding.

res.setEncoding('binary')


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

3 Comments

Windows still can't open this file.
I can't test this at the moment, which is why there was a small bug in the code I supplied. The writeFile takes an object as an option and not just a string. Still can't test this, but that might be the issue.
any update on this? what and how to provide the encoding for saving image?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.