Is there someway I can download an image from request and save it to a variable?
request.head(url, function(err, res, body){
request(url).pipe(fs.createWriteStream(image_path));
});
right now I'm piping
the result to a write stream. But instead I would like to save it to a variable so I can use it in my program. Is there any way to do this?
As what you request is an image, so you can get the response as Buffer .
var request = require('request'), fs = require('fs');
request({
url : 'http://www.google.com/images/srpr/logo11w.png',
//make the returned body a Buffer
encoding : null
}, function(error, response, body) {
//will be true, body is Buffer( http://nodejs.org/api/buffer.html )
console.log(body instanceof Buffer);
//do what you want with body
//like writing the buffer to a file
fs.writeFile('test.png', body, {
encoding : null
}, function(err) {
if (err)
throw err;
console.log('It\'s saved!');
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.