-2

I have to read data from file and then verify if the data email matches. Once it does I use a boolean to store the value. I get output as "It matches" but the user variable is still 'false', which should become true.

  let user = false;
  const filename = path.resolve(__dirname, "../../users.txt");
  newvar = fs.readFile(filename, "utf8", function(err, data) {
    if (err) {
      console.log(err);
    }
    const lines = data.split("\n");

    for (i = 0; i < lines.length; i++) {
      fileArray = lines[i].split("|");
      fileName = fileArray[0];
      fileEmail = fileArray[1];
      filePasswordHash = fileArray[2];
      if (email === fileEmail) {
        console.log("It Matches");
        user = true;
      }
    }
  });

  console.log(user);
Lucifer
  • 488
  • 4
  • 12
  • 1
    I am assuming `readFile` is `async` hence the `callback`. So your `console.log` is executing before the `callback` – Bibberty May 24 '19 at 18:19
  • 1
    `fs.readFile` is a asynchronous operation, that means, by the time `readFile` is done you are already at `console.log(user)`. You can, however, use `fs.readFileSync` to get the expected outcome BUT synchronous operations should be avoided in NodeJS because they block the Event Loop. The only time they are allowed are when you are starting an app, to load files, configurations and such and that's it. – darklightcode May 24 '19 at 18:19
  • But I really need that data that is changing inside the callback outside the function, how can I get that? – Lucifer May 24 '19 at 18:21
  • Also look here: https://stackoverflow.com/questions/46867517/how-to-read-file-with-async-await-properly @Lucifer you need this link. – Bibberty May 24 '19 at 18:21
  • Also https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron. – melpomene May 24 '19 at 18:22
  • @Lucifer Given that the outside code runs before your callback is invoked, you need a time machine. – melpomene May 24 '19 at 18:23
  • @melpomene I have tried writing await for all the function calls inside the async function, but nothing seems to work – Lucifer May 24 '19 at 18:24
  • `await` inside the callback will NOT help. You need to `Promisify` the call to `readfile` – Bibberty May 24 '19 at 18:26
  • @Bibberty how do I do that? sorry if come as bit of a noob in Javascript! – Lucifer May 24 '19 at 18:30
  • 1
    Have a look at the dupes. – Jonas Wilms May 24 '19 at 18:40
  • @Lucifer look at the link I put above, they are doing exactly what you need. – Bibberty May 24 '19 at 18:49

1 Answers1

0

Your last line

console.log(user);

is not working as you have expected because the when the function console.log(user) executes the value user isn't changed, i.e the callback function isn't executed yet.

ajit kumar
  • 564
  • 8
  • 16