下载图像不起作用:NodeJS

时间:2016-05-30 18:01:07

标签: node.js image download

我在Node中编写了一个小功能,用于从服务器下载图像并将其保存在我的服务器上,但它不起作用。图像文件已创建,但似乎已损坏,这是函数:

function d() {
    var data = [
        {
            img: "http://wow.zamimg.com/images/hearthstone/cards/enus/original/OG_134.png",
            cardId: "yogg"
        },
        {
            img: "http://wow.zamimg.com/images/hearthstone/cards/enus/original/HERO_07.png",
            cardId: "nzoth"
        }
    ];
    for(var card of data) {
        if("img" in card) {
            var img = require('fs').createWriteStream("./public/assets/pics/" + card.cardId + ".png");
            require("http").get(card.img, (res) => {
                res.pipe(img);
            });
        }
    }
}

我做错了什么?

2 个答案:

答案 0 :(得分:1)

问题是您的进程在下载完成之前退出。 http.get函数并行运行,因此您需要以某种方式处理它。您可以使用async模块执行此操作。

function d() {
var data = [
    {
        img: "http://wow.zamimg.com/images/hearthstone/cards/enus/original/OG_134.png",
        cardId: "yogg"
    },
    {
        img: "http://wow.zamimg.com/images/hearthstone/cards/enus/original/HERO_07.png",
        cardId: "nzoth"
    }
];
var async = require('async')
async.each(data, (card, next) => {
    if("img" in card) {
        var img = require('fs').createWriteStream(card.cardId + ".png");
          require("http").get(card.img, (res) => {
              res.pipe(img).on('end', next)
          });
    }
}
, () => {
  console.log(done)
})
}

答案 1 :(得分:1)

使用此:

var fs = require('fs'),
    request = require('request');

var download = function(uri, filename, callback){
  request.head(uri, function(err, res, body){
    console.log('content-type:', res.headers['content-type']);
    console.log('content-length:', res.headers['content-length']);

    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
  });
};

download('https://www.THE_URL.com/image.png', 'THE_NAME.png', function(){
  console.log('Image saved!');
});