使用请求从 url 下载图像并保存到变量

Loo*_*urr 2 javascript pipe stream request node.js

有什么办法可以从请求中下载图像并将其保存到变量中吗?

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

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

});
Run Code Online (Sandbox Code Playgroud)

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

And*_*rew 5

由于您请求的是图像,因此您可以将响应作为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!');
    });

});
Run Code Online (Sandbox Code Playgroud)