Answer the question
In order to leave comments, you need to log in
Why can't I add the search result to an array?
I have a function that recursively searches for files by extension, everything works fine, but I can't add the search result to the array
let result = []
let walk = function (dir) {
fs.readdir(dir, function (err, list) {
list.forEach((item) => {
let itemPath = path.join(dir, item);
fs.stat(itemPath, (e, stats) => {
if (stats.isDirectory()) {
walk(itemPath);
} else {
if(extension(itemPath)){
// console.log(itemPath)
result.push(itemPath)
}
}
});
});
})
}
walk(pathSupplied)
console.log(result)
Answer the question
In order to leave comments, you need to log in
Because fs.readdir is asynchronous. At the time of the console log, it has not yet been executed.
Either rewrite to async / await, or to promises, or (at the very least, if you understand what it threatens) use synchronous readdirSync.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question