Victor
Victor

Reputation: 152

Problems with declaring a Cheerio variable

I want to declare the variable $ to the cheerio.load function inside my object so that I can then access the cheerio functions from any of my functions.

However whenever I do I get the error this.$ is not a function

The code I'm using

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

I'm guessing instead of making a variable $ in my object it's making it for the main function only, I've read online to use the context keyword but that doesn't seem to do anything either and I'm unable to find another solution

Upvotes: 0

Views: 138

Answers (1)

0xLogN
0xLogN

Reputation: 3805

readFile is async, so the function call happens before the file loads. Do this:

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

Upvotes: 1

Related Questions