prc322 prc322 - 1 month ago 18
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('http://upload.wikimedia.org/wikipedia/commons/8/8c/JPEG_example_JPG_RIP_025.jpg', 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
var request = require('request'), 
    fs      = require('fs'),
    url     = 'http://upload.wikimedia.org/wikipedia/commons/8/8c/JPEG_example_JPG_RIP_025.jpg';

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