prc322 prc322 - 1 year ago 95
Javascript Question

Cannot save a remote image with node.js and request

I want to save an image with node.js and the request library. So far I have this simple code:

var request = require('request');
var fs = require('fs');

request('', function(error, response, body)
// further logic that decides
// whether or not the image will be saved

fs.writeFile('downloaded.jpg', body, function(){});

But it doesn't work. The image always arrives corrupt. I assume it's an encoding error but I cannot figure out how to fix this.

Answer Source
var request = require('request'), 
    fs      = require('fs'),
    url     = '';

request(url, {encoding: 'binary'}, function(error, response, body) {
  fs.writeFile('downloaded.jpg', body, 'binary', function (err) {});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download