Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

365
Views
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())

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!