Upload image with node -request and fs Promisified, no pipe in Node.js

I am trying to succeed in uploading an image without associating it with fs. Here is what I did:

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 () { ... }) // ... } 

Valid input can be:

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

I really think the problem is with body processing. I tried to make it in Buffer ( new Buffer(body, 'binary') , etc.) In several encodings, but all failed.

Thanks for the help!

+7
promise bluebird fs node-request
source share
1 answer

You must tell request that the data is binary:

 requestAsync(uri, { encoding : null }) 

Documented here :

encoding - The encoding that will be used when encoding setEncoding response data. If null, the body returns as a buffer. Everything else ( including the default value undefined ) will be passed as the encoding parameter toString () (this means that by default it is utf8).

Thus, without this option, body data is interpreted as UTF-8 encoded, which are not (and result in an invalid JPEG file).

+15
source share

All Articles