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 awaiting 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.