最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Download image from url using request and save to variable - Stack Overflow

programmeradmin1浏览0评论

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?

Share Improve this question edited Mar 5, 2014 at 2:07 sachleen 31.1k8 gold badges80 silver badges75 bronze badges asked Mar 5, 2014 at 2:05 LoourrLoourr 5,12510 gold badges45 silver badges69 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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./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!');
    });

});
发布评论

评论列表(0)

  1. 暂无评论