Reputation: 19664
I'm trying to download and image from using http.get in nodejs. The image appears to download but it cannot be opened. The OS complains the file's format appears incorrect. Can someone tell me what I doing wrong here?
Heres an example where I am just trying to grab the Google logo:
var options = {
host:'www.google.com',
port:80,
path:'/images/srpr/logo3w.png'
};
var downloadImage = function (options, fileName) {
http.get(options, function (res) {
var imageData;
res.setEncoding('binary');
res.on('data', function (chunk) {
imageData += chunk;
});
res.on('end', function () {
fs.writeFile(fileName, imageData, 'binary', function(err){
if(err) throw err;
console.log('File: ' + fileName + " written!");
})
});
});
};
downloadImage(options,'test.png');
Upvotes: 2
Views: 2982
Reputation: 6712
The code looks good except for initialization of imageData.
var imageData = '';
should resolve the issue. https://stackoverflow.com/a/5294619/1135590 has a more elaborate discussion.
Upvotes: 1