node.js大量请求抛出错误

时间:2015-07-13 20:35:42

标签: javascript arrays node.js request

我的图像下载程序脚本遇到了一些麻烦,所以我的数组有图像名称(大小约为5000个元素),我在数组中循环,每次迭代下载带有请求模块的图像。

一切正常,但只有那时我的数组大小不超过500 + - 元素。

如果我运行带有5000多个元素的脚本,我会看到许多错误从请求模块(错误或未定义的响应对象)发出,并且所有应用程序都可能因EMPTY FILE ERROR而失败。我认为有一些异步问题导致NODE.JS没有处理这么多操作。

也许我可以通过将大型5000大小的数组拆分300项来解决它,并且不要在上一个块之前的下一个chunck上迭代(并且不要调用fetchImage())。或者也许有更好的方法来解决我的问题。?

products.map(function (product) {
        fetchImage(product.imageUrl,'./static/' + product.filename + '_big.', 0, 0);
        return;
    });

function fetchImage(url, localPath, index, iteration) {
    var extensions = ['jpg', 'png', 'jpeg', 'bmp' , ''];

    if (iteration > 2 || index === extensions.length) { // try another extensions
        iteration++;
        if(iteration < 3) {
            setTimeout(function(){
                fetchImage(url, localPath, 0, iteration);
            }, 3000);
        }else{
            console.log('Fetching ' + url + ' failed or no image exists ');
            return;
        }
        return;
    }

    var fileExtension;

    if(extensions[index] === '' ) {
        fileExtension = extensions[0];
    }else{
        fileExtension = extensions[index];
    }

    request.get(url + extensions[index], function(err,response,body) {

        if(err || undefined === response){   // if err try after 3 sec timeout
            setTimeout(function(){
                console.log('Error URL : ' + url + extensions[index]);
                fetchImage(url, localPath, index, iteration);
            }, 3000);
            return;
        }else{
            if(response.statusCode === 200) {
                request(url + extensions[index])                  
                    .on('error', function(err) {
                        console.log("ERRRRRROR " + url + extensions[index] + " " + err);
                        setTimeout(function(){
                            console.log('Error URL : ' + url + extensions[index]);
                            fetchImage(url, localPath, index, iteration);
                        }, 3000);
                        return;
                    })
                    .pipe(fs.createWriteStream(localPath + fileExtension ));// write image to file

                console.log('Successfully downloaded file ' + localPath + fileExtension);
                return;
            }else {
                fetchImage(url, localPath, index + 1, iteration);
            }
        }
    });
};

1 个答案:

答案 0 :(得分:0)

使用每个请求之间的setTimeOut修复

setTimeout(
            function () {
                fetchImage(imageUrl,'./static/' + filename + '_big.', 0, 0);
            },
                300 * (i + 1) // where they will each progressively wait 300 msec more each
        );