声明 Cheerio 变量的问题

Problems with declaring a Cheerio variable

我想在我的对象内向 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 关键字但是这似乎也没有做任何事情,我无法找到另一个解决方案

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;
    }
};