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


i have been struggling succeed in downloading image without piping fs. here's 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 believe problem handling of body. have tried casting buffer (new buffer(body, 'binary') etc.) in several encodings, failed.

thanks ahead help!

you have tell request data binary:

requestasync(uri, { encoding : null }) 

documented here:

encoding - encoding used on setencoding of response data. if null, body returned buffer. else (including default value of undefined) passed encoding parameter tostring() (meaning utf8 default).

so without option, body data interpreted utf-8 encoded, isn't (and yields invalid jpeg file).


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -