Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

366
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda