A few things happening here:
- I assume you need fs / http and set the dir variable :)
- google.com redirects to www.google.com, so you save the body of the redirect response, not the image
- the answer is transmitted. this means that the data event is triggered many times, not once. you need to save and combine all the pieces together to get the full response body.
- since you get binary data, you need to set the encoding in response and writeFile, respectively (by default - 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.') }) }) })
Ricardo Tomasi Mar 14 '11 at 4:08 2011-03-14 04:08
source share