Search code examples
javascriptnode.jsheroku

Heroku Cannot read properties of undefined (reading 'length')


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"
  },

Solution

  • 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.