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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-18 22:35:21

问题


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!


回答1:


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).



来源:https://stackoverflow.com/questions/31289826/download-an-image-using-node-request-and-fs-promisified-with-no-pipe-in-node-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!