prc322 prc322 - 13 days ago 5x
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.

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

request(url, {encoding: 'binary'}, function(error, response, body) {
  fs.writeFile('downloaded.jpg', body, 'binary', function (err) {});