T
T
timonck2019-12-16 12:13:24
JavaScript
timonck, 2019-12-16 12:13:24

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)

How can this be fixed and is this function correct at all?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
smilingcheater, 2019-12-16
@smilingcheater

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 question

Ask a Question

731 491 924 answers to any question