Home > Software engineering >  Heroku Cannot read properties of undefined (reading 'length')
Heroku Cannot read properties of undefined (reading 'length')

Time:10-09

my Nodejs app working fine on my local machine , when i depoly it to heroku , app crush with Error :

Cannot read properties of undefined (reading 'length')

 function getRandom() {

    return new Promise((resolved,rejected)=>{

        // kick async work 
        fs.readdir(testFolder, (err, files) => {

            let random = files[Math.floor(Math.random() * files.length)]
            console.log("Random is "   random);
            resolved(random)
            //  rejected(new Error("Message "))
    
        });

    })

} 

on package.json i am using

"engines": {
    "node": "16.17.0"
  },

CodePudding user response:

The variable files might be undefined in the readdir callback if there is an error (which would be located in the err variable); to know what the error is, you should add a line in your readdir callback like this:

        // kick async work 
        fs.readdir(testFolder, (err, files) => {
            if (err) {
               console.error(err)
               reject(err)
               return;
            }
            let random = files[Math.floor(Math.random() * files.length)]
            console.log("Random is "   random);
            resolved(random)
            //  rejected(new Error("Message "))
    
        });

My suspicion is the error has to do with the folder not existing on Heroku, but you should run that code and check the logs to be sure.

  • Related