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

261
Visualizações
In node js, how do i implement a callback inside a recursive function?

Im trying to make a program that reads all the files on your computer and put their paths inside an array. However, the function is recursive and I don't know how to log the results once the function is done.

Obviously i need some sort of callback, but I have tried several different approaches and the callback function ends up running before the result is complete. Also, I want the callback function to only run once (when the recursive function is done).

This is my code right now, how do i insert a callback function into the readAllFolders function?

const testFolder = "C:/"; 
const fs = require('fs');

function readAllFolders(path){
    var returnArr = [];
    fs.promises.readdir(path, (err, files) => {
        if(err){
            return;
        }

        files.forEach(file => {
            try{
                var filePath = path + file;
                if(fs.existsSync(filePath) && fs.lstatSync(filePath).isDirectory()){
                     readAllFolders(filePath + '/');
                }else{
                    returnArr.push(filePath);
                }
            }catch(e){

            }
        });
  });

  return returnArr;
}


var arr = readAllFolders(testFolder);
console.log(arr);

about 4 years ago · Juan Pablo Isaza
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