0

so I have a function which open a txt file, extracts some lines and returns an array.

Problem is, it doesn't..

I console.log'd the last line before the return which printed an array, so I'm confused.

Tried console.logging everything but for some reason it will ALWAYS RETURN UNDEFINED

function Collect_Games(Amount){

    let Msg = "",
    userkeys = [];

    fs.readFile("./SETTINGS/games.txt", "utf8", (error, data) => {

        if(error) {
            return;
        } else {
            let keys = data.split("\n");


            if(keys.length < Amount) {

                dont = false;

                Msg = "I don't have enough keys for you, please try again later..";
            } else {

                 userkeys = keys.splice(0, Amount);
                /*
                for(var i=0 ; i < userkeys.length ; i++){
                    Msg+= userkeys[i]+"\r\n";
                }*/


                fs.writeFile("./SETTINGS/games.txt", keys.join("\n"), error => {

                    if(error) {

                    }
                    console.log(userkeys); // this actually prints an array..
                    return userkeys;

                });
            }
        }
    });
}

Expecting this: console.log(Collect_Games(3)); to return an array, however it returns undefined

deceze
  • 510,633
  • 85
  • 743
  • 889
kmp 2d
  • 1
  • 2
  • the code is cut out for some reason, but imagine it's not (dunno how 2 fix that) – kmp 2d Feb 01 '19 at 08:04
  • Maybe Amount is bigger than keys.length, hence it doesn't return anything. And as Asim mentioned, you need to return readFile. – Prem Raj Feb 01 '19 at 08:06

1 Answers1

-1

write a return state before fs.readFile as below.

return fs.readFile("./SETTINGS/games.txt", "utf8", (error, data) => {
Asim Khan
  • 1,969
  • 12
  • 21
  • If that's what you meant, it returns an empty array: }); // fs.read file ends here return userkeys; – kmp 2d Feb 01 '19 at 08:08
  • It depends on your this line "userkeys = keys.splice(0, Amount);". check what is wrong with your data or logic. as I dont know which kinda data do you have – Asim Khan Feb 01 '19 at 08:10