Friday, 12 May 2017

How to prevent NodeJS heap out of memory

I have the following error:

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

Which is a result of the following code:

const _secret = 'NICHOLAS';

const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

const maxLen = 8;

const maxGuesses = 999999999;

let answer;

let guess = '';

let curGuesses = 0;

function doCheck(passwordToReverseEngineer){
        function getRand(){
                return charset.split('')[Math.floor(Math.random() * charset.length)];
        };

        while (guess !== _secret){
                if (guess.length <= maxLen){
                        ++curGuesses;
                        guess += getRand();
                        console.log(`Now trying this combo: ${guess}`);
                }
                else if (curGuesses === maxGuesses) {
                        throw new Error(`Limit of ${maxGuesses} has been reached.`);
                }
                else {
                        guess = '';
                }

                setTimeout(()=>{
                        doCheck(passwordToReverseEngineer);
                });
        }

        answer = guess;

        console.log(`The secret has been cracked and it is ${guess} after ${curGuesses} attempts.`);

        return true;
}

How could I avoid this so that the server can handle n number of guesses before reaching an out of memory exception such as the one above?



via Alpha G33k

No comments:

Post a Comment