Search code examples
node.jsdiscord.js

FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory(i have set the max-old-space-size already) discord.js node.js


I keep getting this error, I have set my max-old-space-size to 8192 or higher and I don't understand what is the problem.

I have tried various types of size too.

This is the main part of the code:

client.on("message", message =>{
    let i = 1;
    while (i < 10) {
        task(i)
    }
    function task(i) {
        setTimeout(function (){
            util.statusBedrock('ip', { port: port, timeout: 3800})
            .then((reponse) =>{
                const Embed = new Discord.MessageEmbed()
                .setColor('#62ff00')
                .setTitle('Server Status')
                .setAuthor('Made by ThatTheredstoner')
                .addField(':green_circle: Online', reponse.version)
                .addField('**Software/System**', reponse.software)
                .addField('Server IP', 'ip')
                .addField('Server Port', reponse.port)
                .addField('Gamemode', 'Survival ')
                .addField('**Latency**', reponse.roundTripLatency)
                .addField('Online Player', reponse.onlinePlayers)
                .addField('Player', reponse.players)
                .addField('Max Players', reponse.maxPlayers)
                .setTimestamp()
                .setFooter('footer');
                        
                client.channels.cache.get('channel').messages.fetch('message').then((mesg)=>{
                    mesg.edit(Embed);
                })
                console.log(reponse);
            })
            .catch((error) => {
                console.log(error)
                const OEmbed = new Discord.MessageEmbed()
                .setColor('#ff0000')
                .setTitle('Server Status')
                .setAuthor('Powered with Redstone')
                .addField(':red_circle:', 'Offline')
                .addField('Server IP', 'ip')
                .setTimestamp()
                .setFooter('footer');
                                
                client.channels.cache.get('channel id').messages.fetch('message id').then((mesg)=>{
                    mesg.edit(OEmbed);
                })  
            })
        }, 4000);
    }
}); 

I swapped out the IDs and IPs for good measurement.


Solution

  • The problem is within your while loop. Variable i is never used or updated. Because of your logic in the while loop, variable i is always below 10 no matter what.

    Because of the never ending loop, and every time someone posts a message, your while loop will stack until there is no memory left on your machine to execute your while() loop, thus it will collapse and crash your application.

    My solution would be as followed: Put your async task outside of the message loop and make a trigger command for it, for example !update server info.

    ! My answer might divergent from your own code, I've made a simulation for an async task as following:

    
    let isBusy = false;
    const tasks = 10;
    const asyncTask = (ms, i) => new Promise(resolve => setTimeout(() => {
        console.log(`Task (${i}) finished in ${ ms / 1000 } seconds.`);
        resolve(true);
    }, ms));
    
    client.on("message", async message => {
        if(message.content === "!update server info") {
    
            if(isBusy === false) {
                isBusy = true;
                let i = 0;
                while(i++ < tasks) {
                    await asyncTask(Math.floor(Math.random() * 5000), i); // THE MATH CALCULATION ON THIS LINE IS TO SIMULATE AN ASYNC TASK! DO NOT USE IN YOUR CODE.
                    if(i >= tasks) isBusy = false;
                }
            }else{
                // Send a message to the user if your tasks are still running or not.
            }
        }
    });
    

    Also in your case you're updating your message frequently, I wouldn't do that as it may result in a rateLimit error. I would update your message only once per 1 or 2 minutes.

    ! This answer might not ideal or best practice, but it should push you to the right direction and understand how while loops work.