0

I have this code which seems to work, but the console output is always "is present", but it's false in one case...

function registerUser(pseudo){
  fs.appendFile('pseudos.txt', pseudo + '\r\n', function (err) {
    if (err) throw err;
  });
}

function isNewUser(pseudo){
  fs.readFile('pseudos.txt', 'utf8', function (err,data) {
    if (err) {
      return console.log(err);
    }
    if (data.includes(pseudo)){
      return true;
    }else{
      return false;
    }
  });
}

async function main() {
   registerUser('toto');
   registerUser('titi');

   if (isNewUser('titi')){
      console.log('titi is new');
   }else{
      console.log('titi is not new');
   }
  if (isNewUser('tutu') == true){
      console.log('tutu is new');
  }else{
      console.log('tutu is not new');
  }

}

The result is :

titi is not new
tutu is not new

But it should be :

titi is not new
tutu is new

What I'm doing wrong ?

Hulk
  • 6,399
  • 1
  • 30
  • 52
user2178964
  • 124
  • 6
  • 16
  • 40
  • 1
    As far as I can see, `isNewUser` does not return anything. And nothing, void etc are falsy in js. The callback does return, but that is not the return value of `isNewUser`. – Hulk Feb 03 '21 at 13:42
  • Both `registerUser` and `isNewUser` have async code and you are not waiting for them to complete before executing logic that is dependent on result of these two functions. I would suggest reading more about asynchronous code in js. – Raeesaa Feb 03 '21 at 13:54
  • Use synchronous functions instead – Kashish Khullar Feb 03 '21 at 13:56
  • @KashishKhullar Synchronous functions block javascript stack and should be avoided as much as possible. – Raeesaa Feb 03 '21 at 14:05
  • In this case, sync would be better. The file is small for now but for large file the async write operation would take time and the read operation would get executed even though the write hasn't finished and would yield an incorrect output. – Kashish Khullar Feb 03 '21 at 14:09
  • To make it simplier, I just want to keep in mind a list of pseudo. I need to keep it even if I stop the program, so I used a file like this, but maybe there is a better solution ? – user2178964 Feb 03 '21 at 14:26

0 Answers0