A few things happening here:
- I assume you required fs/http, and set the dir variable 🙂
- google.com redirects to www.google.com, so you’re saving the redirect response’s body, not the image
- the response is streamed. that means the ‘data’ event fires many times, not once. you have to save and join all the chunks together to get the full response body
- since you’re getting binary data, you have to set the encoding accordingly on response and writeFile (default is utf8)
This should work:
var http = require('http')
, fs = require('fs')
, options
options = {
host: 'www.google.com'
, port: 80
, path: '/images/logos/ps_logo2.png'
}
var request = http.get(options, function(res){
var imagedata=""
res.setEncoding('binary')
res.on('data', function(chunk){
imagedata += chunk
})
res.on('end', function(){
fs.writeFile('logo.png', imagedata, 'binary', function(err){
if (err) throw err
console.log('File saved.')
})
})
})