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?
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?
1 Answer
Reset to default 9As 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./images/srpr/logo11w.png',
//make the returned body a Buffer
encoding : null
}, function(error, response, body) {
//will be true, body is Buffer( http://nodejs/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!');
});
});