javascript - 不能一起执行的功能

标签 javascript node.js request cheerio

我最近在构建一个 scraper 模块以使用 nodejs 获取一些信息,直到我遇到了这个“小”问题。我使用的模块是 cheeriojs 和 request。 实际上,如果我一次只调用一个方法,该模块就像一个魅力。它包含三个函数,其中只有两个被导出,这是代码:

'use strict';

var request = require('request'),
    cheerio = require('cheerio'),
    counter = 0;

function find(term, cat, callback) {
  // All the check for the parameters
  scrape("http://.../search.php?search=" + encodeURIComponent(term), cat, callback);
}

function last(cat, callback) {
  // All the check for the parameters
  scrape("http://google.com/", cat, callback);
}

function scrape(url, cat, callback) {
  request(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var $ = cheerio.load(body);
      var result = [];

      var items = $('.foo, .foo2').filter(function() {
        // Condition to filter the resulted items
      });

      items.each(function(i, row) {
        // Had to do another request inside here to scrape other information
        request( $(".newpagelink").attr("href"), function(error, response, body) {
          var name = $(".selector").text(),
              surname = $(".selector2").text(),
              link = cheerio.load(body)('.magnet').attr('href'); // This is the only thing that I'm scraping from the new page, the rest comes from the other "cheerio.load"
        // Push an object in the array
        result.push( { "name": name, "surname": surname, "link": link } );

          // To check when the async requests are ended
          counter++;
          if(counter == items.length-1) {
            callback(null, result);
          }
        });
      });
    }
  });
}

exports.find = find;
exports.last = last;

正如我所说,现在的问题是,如果我创建一个新的 Node 脚本“test.js”并且我只调用 last OR find,它会完美运行!但是如果我像这样连续调用这两种方法:

var mod = require("../index-tmp.js");
mod.find("bla", "blabla", function(err, data) {
    if (err) throw err;
    console.log(data.length + " find");
});
mod.last(function(err, data) {
  console.log(data.length + " last");
});

结果完全乱七八糟,有时脚本甚至不打印任何东西,有时只打印“find”或“last”的结果,有时返回 cheeriojs 错误(我不会在这里添加到不要惹你生气,因为这可能是我的脚本的错)。我还想为这两种方法重复相同的功能两次,但没有,同样的问题发生了......我不知道还能尝试什么,我希望你能告诉我这种行为的原因!

最佳答案

您的counter 变量是全局的,不特定于每个scrape 调用。如果您同时调用两次 findlast,它将无法工作。

var counter = 0; 的声明和初始化移动到 scrape 函数中,或者更好的是紧挨着 result项目声明。

关于javascript - 不能一起执行的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34352883/

相关文章:

javascript - 如何使用 Electron 本地快捷方式执行 'cut'

javascript - 在不兼容的接收器nodejs上调用类型错误: Method Uint8Array.长度

javascript - 如何使 Hapi 插件仅适用于特定域或子域?

javascript - 如何将 Angular 和 Vue 项目合并在一起?

javascript - 从 JSON 渲染多个 Google Maps API V3 标记

javascript - 为什么我会收到这个已弃用的警告?! MongoDB

javascript - 下拉菜单栏 Slidedown 意外错误

python - 有没有办法在不下载 Python 中的 url 内容的情况下获取响应 header ?

java - 记录来自 java 服务的请求-响应

javascript - 使用 node.js 在 Mocha 中执行 REST 调用