D
D
Denisca Gareev2020-05-19 18:10:09
Node.js
Denisca Gareev, 2020-05-19 18:10:09

How to fix fs.readdir() issue?

The goal is this: you need to get folders and files in a folder, for example test_dir, and if there is a folder named dir1, then change the ok variable to true:

var ok = false;
fs.readdir("./test_dir", function(err, data){
    if(err){ throw err };
    for(i in data){
        if(data[i] == "dir1"){
            ok = true;
        }
    }
}

Problem: ok variable stays the same
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dima Polos, 2020-05-19
@dimovich85

You are correct in your comments. After starting the folder reading function, everything happens asynchronously, therefore, reading the ok variable immediately after starting the folder reading, you get false, but when the callback works, then it will be true. You need to translate this logic completely into asynchronous mode. Reading a folder can be wrapped in a Promise, and declaring a variable and reading its value can be wrapped in an asynchronous function.

const readdir = path => (
      new Promise( (resolve, reject) => {
         fs.readdir( path, (err, data) => err ? reject(err) : resolve(data) );
      });
);

(async ()=>{
  let ok = false;
  try{
    let data = await readdir('./test_dir');
    ok = data.includes('dir1');
    console.log(ok);
  } catch(e){
    console.log(e);
  }
})();

PS: after your code started to work asynchronously - you need to do asynchronously everything that depends on asynchronous code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question