Answer the question
In order to leave comments, you need to log in
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;
}
}
}
Answer the question
In order to leave comments, you need to log in
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);
}
})();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question