Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

364
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda