Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

112
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);

7 months ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.