Node.js限制并发连接(请求)

时间:2015-11-04 15:05:15

标签: node.js request cheerio

我正在使用Request,Cheerio和Node.js

我需要将并发请求限制为10.我想并行处理URL,但不能同时处理,希望它清楚。

这是我目前的剧本。如果我将for循环从0运行到100,它就可以工作。 100到200,它的工作原理。 200至300,它的工作原理。 但是0-1000给出了连接错误。我需要设置限制,以便一次可以处理5个或10个请求。

app.get('/back', function (req, res) {
    for (var y = 0; y < 1000; y++) {
        (function () {
            const id = y;
            var url = "http://www.example.com/" + y;
            var options2 = {
                url: url,
                headers: {
                    'User-Agent': req.headers['user-agent'],
                    'Content-Type': 'application/json; charset=utf-8'
                }
            };

                request(options2, function (err, resp, body) {
                    if (err) {
                        console.log(err);
                    } else {
                        if ($ = cheerio.load(body)) {
                            var links = $('#container');
                            var name = links.find('span[itemprop="name"]').html(); // name
                            if (name == null) {
                                console.log("null returned");
                            } else {
                                name = entities.decodeHTML(name);
                                // check name existence
                                console.log("yay!" + name);
                                    }
                                });
                            }
                        }
                        else {
                            console.log("couldn't open it");
                        }
                    }
                }
            );
        }());
    }
});

0 个答案:

没有答案
相关问题