Recursive function in node.js giving unexpected results

Well the results are unexpected for me at least. I'm trying to search through a directory and get all files and subfolders, however I'm having some problems with working with subdirectories of subdirectories. The function itself is designed to find all the contents of all the folders and all the files within a given folder, and call itself when one of the things inside a folder is a folder.

However, it never finishes, it keeps feeding the same folder into itself and never doing anything with it, eventually just crashing.

var fs = require('fs');

var array = fs.readdirSync(__dirname);
function getAllSub(array){
for (i = 0; i < array.length; i++){
    if (array[i].indexOf(".") == (-1))
        {                     
            array = array.concat(array[i] + "/" + fs.readdirSync(__dirname + "/" +    array[i]));
        }
    if (array[i].indexOf("/") != (-1)){
        var foldcon = array[i].substr(array[i].indexOf("/") + 1);
        var folder = array[i].substr(0, array[i].indexOf("/"));
        foldcon = foldcon.split(",");
        for (n = 0; n < foldcon.length; n++){
            foldcon[n] = folder + "/" + foldcon[n]
            if (foldcon[n].indexOf(".") == (-1)){ 
                console.log([foldcon[n]]);
                foldcon[n] = getAllSub([foldcon[n]]);          

            }
        }
        array.splice(i, 1, foldcon);

    }

}


return array;
}
array = getAllSub(array);
console.log(array);

You have a couple of problems with your code. You should be using the fs.stat call to get information about files to determine if they are directories or files, parsing the paths themselves is really error prone. Also, readdir just returns the names of the file in the directory, not the full path to the files. Finally, I'd suggest you use the async versions of readdir so that you don't lock up the node.js thread while you're doing this.

Here's some sample code for getting all of the folders and files from a start path:

var parseDirectory = function (startPath) {
  fs.readdir(startPath, function (err, files) {
    for(var i = 0, len = files.length; i < len; i++) {
      checkFile(startPath + '/' + files[i]);
    }
  });
};

var checkFile = function (path) {
  fs.stat(path, function (err, stats) {
    if (stats.isFile()) {
      console.log(path + ' is a file.');
    }
    else if (stats.isDirectory()) {
      console.log(path + ' is a directory.');
      parseDirectory(path);
    }
  });
};


parseDirectory(__dirname + '/../public');