简体   繁体   中英

Node.js: Push File Names into an Array in an Async-Await Way?

I would like to get some help because I just can not figure out how to use an async-await methods recursively in Node.js.

I am trying to create a function that returns all the files in all subfolders as an array using the file-system module.

I did saw a lot of examples online, but none of these used an array and than waited for an answer.

Thanks!

 function checkFiles () { const files = [] const getFiles = async dir => fs.readdir(`./${dir}`, { withFileTypes: true }, (err, inners) => { if (err) { throw new Error (err) } else { inners.forEach(inner => { inner.isDirectory()? getFiles(`${dir}/${inner.name}`): files.push(`file: ${inner.name}`); }); }; }); getFiles('.') if (files.length === 0) { return 'no files' } else { return files } } console.log(checkFiles())

You are invoking getFiles asynchronously, and within getFiles you pass a callback to readdir instead of await ing it. What you should try is adding await to both lines:

function checkFiles() {
    const files = []
    const getFiles = async dir => {
        try {
            inners = await fs.readdir(`./${dir}`, { withFileTypes: true })
            inners.forEach(inner => {
                inner.isDirectory() ? getFiles(`${dir}/${inner.name}`) : files.push(`file: ${inner.name}`);
                });
        } catch {
            // handle error
        }
    };
    await getFiles('.')
    
    if (files.length === 0) {
        return 'no files'
    }
    return files
}

This will cause the program to halt when reaching getFiles() , and continue the execution only after it has finished, meaning files is ready for usage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM