Skip to content Skip to sidebar Skip to footer

Storing Images Using Node.js Gives Error

I am trying to get an image from wikimedia and the link of the image is upload.wikimedia.org/wikipedia/commons/thumb/e/e3/AybükeArslan_(3).JPG/220px-AybükeArslan_(3).JPG But whe

Solution 1:

Because you have uncoded string in url. Use encodeURI

UPDATED

var http = require('https')
  , fs = require('fs')
  , options;

options = {
    hostname: 'upload.wikimedia.org'
  , port: 443
  , path: encodeURI('/wikipedia/commons/thumb/e/e3/AybükeArslan_(3).JPG/220px-AybükeArslan_(3).JPG')
};

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

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

    res.on('end', function(){
       console.log(imagedata);
    });

    //trying to store the response as a jpg image which i am failing miserably because the response is a error statement rather than image stream. 
    res.on('end', function(){
        fs.writeFile('image.jpg', imagedata, 'binary', function(err){
            if (err) throw err;
            console.log('File saved.');
        });
    })
});

Solution 2:

I Asked a separate question to find the answer, There is some problem with hidden characters which are not visible in sublime, That causes the error, In the question the code i mentioned was completely right, For further details read below answer

String has hidden characters, Can't able to verify ,

Post a Comment for "Storing Images Using Node.js Gives Error"