Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download an image using node-request, and fs Promisified, with no pipe in Node.js

I have been struggling to succeed in downloading an image without piping it to fs. Here's what I have accomplished:

var Promise = require('bluebird'),
    fs = Promise.promisifyAll(require('fs')),
    requestAsync = Promise.promisify(require('request'));

function downloadImage(uri, filename){
    return requestAsync(uri)
        .spread(function (response, body) {
            if (response.statusCode != 200) return Promise.resolve();
            return fs.writeFileAsync(filename, body);
        })
       .then(function () { ... })

       // ...
}

A valid input might be:

downloadImage('http://goo.gl/5FiLfb', 'c:\\thanks.jpg');

I do believe the problem is with the handling of body. I have tried casting it to a Buffer (new Buffer(body, 'binary') etc.) in several encodings, but all failed.

Thanks from ahead for any help!

like image 955
Selfish Avatar asked Jul 08 '15 10:07

Selfish


People also ask

How do I download a node js file?

Method 1: Using 'https' and 'fs' module We can use the http GET method to fetch the files that are to be downloaded. The createWriteStream() method from fs module creates a writable stream and receives the argument with the location of the file where it needs to be saved.

What is request on in Nodejs?

The on method binds an event to a object. It is a way to express your intent if there is something happening (data sent or error in your case) , then execute the function added as a parameter. This style of programming is called Event-driven programming.


Video Answer


1 Answers

You have to tell request that the data is binary:

requestAsync(uri, { encoding : null })

Documented here:

encoding - Encoding to be used on setEncoding of response data. If null, the body is returned as a Buffer. Anything else (including the default value of undefined) will be passed as the encoding parameter to toString() (meaning this is effectively utf8 by default).

So without that option, the body data is interpreted as UTF-8 encoded, which it isn't (and yields an invalid JPEG file).

like image 113
robertklep Avatar answered Oct 23 '22 22:10

robertklep