Question

I'm trying to write a recursive file listing function. It works, except for the recursive part; It gets stuck in a loop forever whenever it reads comes along a folder. For example:

The folder C:/Server contains several text files, and one folder. The program will log the file, but when it sees the folder, it will consistently alternate between outputting:

C:/Server/Dir

and

C:/Server/Dir/text.txt

Here's the code:

var fs = require('fs');

var paths = {};

function findPaths(dir)
{
  var thisdir = fs.readdirSync(dir);
  for(Index = 0; Index < thisdir.length; Index++)
    {
      console.log(dir+"/"+thisdir[Index]);
      if(fs.statSync(dir+"/"+thisdir[Index]).isDirectory())
        {
            paths[dir+"/"+thisdir[Index]] = "directory";
            findPaths(dir+"/"+thisdir[Index])
        }
      else
        {
            paths[dir+"/"+thisdir[Index]] = "file";
        }
    }
}

findPaths("C:/Server");

console.log("FINISHED!");

Please don't link to libraries within your response; I don't want bloated software to cover my ignorance.

Was it helpful?

Solution

your Index is a global variable - this does not work well with recursion. Change it to be local:

for(var Index = 0; Index < thisdir.length; Index++)
  {
     // ...
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top