0

I have this snippet of code from my recent project, I am wondering why this returns false when I provide the correct input. I have put console logs everywhere and checked everything. I tried using global varibles, temp varables, all of that and nothing has worked so far.

var directoryPath = path.join(__dirname, 'images');
  var result = false;

  fs.readdir(directoryPath, function (err, files) {
    var local = false;

    //handling error
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    }
    //listing all files using forEach
    files.forEach(function (file) {
        // Do whatever you want to do with the file

        if(file == password) {
          result = true;
        }
      });

  });
  return result
Kai
  • 3
  • 3

1 Answers1

1

It may seem to you like result is true, but the single thread that runs your code sees something more along the lines of

var result = false
fs.readdir(directoryPath, function (err, files) => {...}) // thread: i'll just set this off
return result // thread: i'll return this immediately

So you're getting false when you really want true. Here's how you can do it with async/await

const main = async (directoryPath, password) => {
  let result = false
  let files
  try {
    files = await fs.promises.readdir(directoryPath)
  } catch (err) {
    return console.log('Unable to scan directory: ' + err);
  }
  files.forEach(file => {
    if (file == password) {
      result = true
    }
  })
  return result // now result will be true if file == password
}
richytong
  • 2,387
  • 1
  • 10
  • 21