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

257
Views
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
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!