0

For example given: '/Users/John/Desktop/FooApp', I would like to get a list such as:

['/Users/John/Desktop/FooApp',
 '/Users/John/Desktop/FooApp/Folder1',
 '/Users/John/Desktop/FooApp/Folder2',
 '/Users/John/Desktop/FooApp/Folder2/folderA',
 '/Users/John/Desktop/FooApp/Folder3',
 '/Users/John/Desktop/FooApp/Folder3/folderX',
 '/Users/John/Desktop/FooApp/Folder3/folderX/folderY',
 '/Users/John/Desktop/FooApp/Folder3/folderX/folderY/folderZ',
 '/Users/John/Desktop/FooApp/Folder3/folderX/folderY2'
]

I require this list to search through all directories to check the existence of a file. The user inputs a folder, and I basically will perform a check similar to finders in OS. I am planning to check fs.exists(subdir + '/mylib.dll') on all the subdirectories. Is there any neat way to do that?

batilc
  • 691
  • 1
  • 5
  • 16

1 Answers1

1

I have converted an answer to a similar question in here, where search was performed for files instead of directories. I also used async to check if file exists. I also found out that fs.exists was about to be deprecated and decided to go on with fs.open.

Anyway, Here is the snippet:

var fs = require('fs');

var getDirs = function(dir, cb){
    var dirs = [dir];
    fs.readdir(dir, function(err, list){
        if(err) return cb(err);
        var pending = list.length;
        if(!pending) return cb(null, dirs);

        list.forEach(function(subpath){
            var subdir = dir + '/' + subpath;
            fs.stat(subdir, function(err, stat){
                if(err) return cb(err);

                if(stat && stat.isDirectory()){
                    dirs.push(subdir);
                    getDirs(subdir, function(err, res){
                        dirs = dirs.concat(res);
                        if(!--pending) cb(null, dirs);
                    });
                } else {
                    if(!--pending) cb(null, dirs);
                }
            });
        });
    });
};

One can then use it as:

var async = require('async');

getDirs('/Users/John/Desktop/FooApp', function(err, list){
    if(err) return 'Error retrieving sub-directories';

    async.detect(list, function(dir, cb){
            fs.open(dir + '/mylib.dll', 'r', function(err, file){
                if(err) cb(false);
                else cb(true);
            });
        }, 
        function(dir) {
            if(!dir) return 'File Not Found';
            /* Do something with the found file ... */
        }
    );
});
Community
  • 1
  • 1
batilc
  • 691
  • 1
  • 5
  • 16