【问题标题】:Problems with declaring a Cheerio variable声明 Cheerio 变量的问题
【发布时间】:2021-07-04 22:37:48
【问题描述】:

我想将变量 $ 声明为对象内的 cheerio.load 函数,这样我就可以从我的任何函数中访问cheerio 函数。

但是,每当我这样做时,我都会收到错误 this.$ is not a function

我正在使用的代码

var spl = {    
    main: function() {
        fs.readFile("index.html", "utf8", function(err, data){
            if(err) throw err;
            this.$ = cheerio.load(data) // Using context.$ resulted in the same problem 
        });
        this.hasTitleTag() // this gives the error this.$ is not a function
    },

    hasTitleTag: function() {
        return this.$('title').length > 0 ? true : false;
    }
};

我猜不是在我的对象中创建一个变量 $,而是仅用于 main 函数,我在网上阅读过使用 context 关键字,但这似乎没有任何作用要么,我无法找到另一个解决方案

【问题讨论】:

  • 您是如何将cheerio 导入您的应用程序的?
  • 另外,仅供参考,readFile 是异步的。它在完成读取文件后调用您的回调。所以this.$ = cheerio.load(data) 在你的其余代码之后执行。
  • constcheerio = require('cheerio');
  • readFileSync 不是异步版本吗?
  • readFileSync 是同步版本。

标签: javascript node.js cheerio


【解决方案1】:

readFile 是异步的,因此函数调用发生在文件加载之前。这样做:

var spl = {    
    main: function() {
        let data = fs.readFileSync("index.html", "utf8");
        this.$ = cheerio.load(data)
        this.hasTitleTag() // this gives the error this.$ is not a function
    },

    hasTitleTag: function() {
        return this.$('title').length > 0 ? true : false;
    }
};

【讨论】:

  • 谢谢,我需要阅读异步和同步 :)
  • @fiji tl;dr: sync = syncronous,它一个接一个地运行 // async = a-syncronous = not-syncronous,它同时运行多个东西
猜你喜欢
  • 2011-06-11
  • 1970-01-01
  • 2011-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-15
  • 1970-01-01
相关资源
最近更新 更多