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!
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With