Home > Net >  TypeError: Cannot read properties of undefined (reading 'length') in nodejs
TypeError: Cannot read properties of undefined (reading 'length') in nodejs

Time:04-04

I am trying to make a discord level bot and I need to grab some ingo from a json file and compare the length but I get the error in the title at if statement:

if(message.author.bot == false && userinput != '!level')
    {   let data = JSON.parse(fs.readFileSync("./level.json", "utf-8"));
        // console.log(data);
        if(data = undefined)
        {
            console.log("data is undefined");
            return;
            //if date is undefined (failsafe method)
        }
        // for loop looping through array, if we are going to find user, we add  1 experience and exit the loop
        if( data.length > 0){
        for(let i=0;i< data.length; i  )
        if(message.author.id == data[i].userID)
        {
            data[i].exp  ;
            fs.writeFileSync("./level.json", JSON.stringify(data));
            i = data.length;
        }
            
        }
        //if file is empty, add user details to file, only run once
        else
        if(data.length <= 0)
        {
        const newuser = {
                    "userID" : message.author.id,
                    "exp" : 1
                }
                data = [newuser];
                fs.writeFileSync("./level.json", JSON.stringify(data));
        }
        
        //is going to add experience to user
        
    }

error log:

    if( data.length > 0){
             ^

TypeError: Cannot read properties of undefined (reading 'length') at Client.<anonymous>

CodePudding user response:

You are assigning (single equals) undefined to data:

if(data = undefined)
        ^^^

If you check with double equals, it will work:

if (data == undefined) { ... }

You can also do if (!data) { ... }.

CodePudding user response:

This is because of if(data = undefined). Please note that there is only one = sign.

Due to this, the data would be assigned as undefined and this line would become if(undefined). Hence the if block won't be executed.

Just update this line to if(data == undefined)

  • Related