sivashanmugam kannan sivashanmugam kannan - 10 days ago 7
Javascript Question

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 when i try to get the image using node.js the wikimedia server gives error statement as response. But on the browser the URL works perfectly and give the image as response.

The is the error statement


400 Bad Request The server could not comply with the request since it
is either malformed or otherwise incorrect. Failed to decode request


And the code is

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

options = {
host: 'upload.wikimedia.org'
, port: 443
, path: '/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.')
})
})

})


Can anybody help? stuck in to it for a long time.

Answer

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 ,

Comments