2014-03-05 95 views
1

有没有办法我可以从request下载图像并将其保存为变量?使用请求从url下载图像并保存到变量

request.head(url, function(err, res, body){ 

    request(url).pipe(fs.createWriteStream(image_path)); 

}); 

现在我piping的结果写入流。但是,我想将它保存到一个变量,所以我可以在我的程序中使用它。有没有办法做到这一点?

回答

2

由于您的要求是一个图像,所以你可以得到的响应为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!'); 
    }); 

});