Node.js -每次循环一个url数组

Node.js - Looping through array of URLS one at a time

本文关键字:一个 url 数组 js 循环 Node      更新时间:2023-09-26

我是node js的初学者,我想写一个网页抓取脚本。我得到了网站管理员的许可,如果我一分钟的请求少于15个,我就可以删除他们的产品。当我开始时,它曾经一次请求所有的url,但经过一些工具,我能够遍历数组中的每个项目,但是当数组中没有更多的项目时,脚本不会停止?我对我的结果不是很满意,觉得有更好的方法来做这件事。

    var express = require('express');
    var fs = require('fs');
    var request = require('request');
    var cheerio = require('cheerio');
    var app     = express();
    var async = require('async');
app.get('/scrape', function(req, res){
productListing = ['ohio-precious-metals-1-ounce-silver-bar','morgan-1-ounce-silver-bar']
var i = 0;
async.eachLimit(productListing, 1, function (product, callback) {
    var getProducts = function () {
        var url = 'http://cbmint.com/' + productListing[i];
        request(url, function(error, response, html) {
            if(!error){
                var $ = cheerio.load(html);
                var title;
                var json = { title : ""};
                $('.product-name').filter(function(){
                    var data = $(this);
                    title = data.children().children().first().text();
                    json.title = title;
                })
            }
            var theTime = new Date().getTime();
            console.log(i);
            console.log(json.title);
            console.log(theTime);
            i++;
        });
    }
    setInterval(getProducts,10000); 
})
res.send('Check your console!')
})
app.listen('8081')
console.log('Magic happens on port 8081');
exports = module.exports = app; 

您没有在迭代器函数中调用callback。看一下eachLimit的文档。