Update
The accepted answer was good for last year but today I would use the package everyone else uses: https://github.com/mikeal/request
Original
I'm trying to grab google's logo and save it to my server with node.js.
This is what I have right now and doesn't work:
var options = { host: 'google.com', port: 80, path: '/images/logos/ps_logo2.png' }; var request = http.get(options); request.on('response', function (res) { res.on('data', function (chunk) { fs.writeFile(dir+'image.png', chunk, function (err) { if (err) throw err; console.log('It\'s saved!'); }); }); });
How can I get this working?
To write an image to a local server with Node. js, we can use the fs. writeFile method. to call res.
A few things happening here:
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.') }) }) })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With