javascriptnode.jsrecursionfilesystemselectron

Node.js recursively list full path of files


Good night everyone. I'm having trouble with probably some simple recursive function. The problem is to recursively list all files in a given folder and its subfolders.

For the moment, I've managed to list files in a directory using a simple function:

fs.readdirSync(copyFrom).forEach((file) => {
  let fullPath = path.join(copyFrom, file);

  if (fs.lstatSync(fullPath).isDirectory()) {
    console.log(fullPath);
  } else {
    console.log(fullPath);
  }
});

I've tried various methods like do{} ... while() but I can't get it right. As I'm a beginner in javascript, I finally decided to ask for help from you guys.


Solution

  • Just add a recursive call and you are done:

     function traverseDir(dir) {
       fs.readdirSync(dir).forEach(file => {
         let fullPath = path.join(dir, file);
         if (fs.lstatSync(fullPath).isDirectory()) {
            traverseDir(fullPath);
         }  
         console.log(fullPath);
       });
     }