user4423309
user4423309

Reputation: 13

Node: Traversing directories in a recursion

I'm pretty new to Node...I need to hammer Node's async behavior and callback structure into my mind. Here where I struggle right now:

   // REQUIRE --------------------------------------------------------------------
   fs      = require('fs');
   path    = require('path');

   // FUNCTION readAllDirs -------------------------------------------------------
   function readAllDirs(dir, result) {
      if (!result) {
            result = function() {};
      };

      fs.readdir(dir, function(err, list) {
            if(err) { return result(err) };

            list.forEach(function(file) {
                    var fullpath = path.resolve(dir, file);

                    fs.stat(fullpath, function(err, stat) {
                            if(err) { return result(err) };

                            if(stat && stat.isDirectory()) {
                                    readAllDirs(fullpath);
                                    //console.log('In: ' + fullpath);
                                    result(null, fullpath);
                            }
                    });
            });
      });
   }

   // MAIN -----------------------------------------------------------------------
   readAllDirs('/somedir', function(err, dirs) {
            console.log(dirs);
   });

I try to traverse a tree of directories. In principle the function is working nice...as long I do not callback but print the directory names on the console. All folders and sub-folders come up as expected. BUT when I do callbacks the callback is not called for recursion deeper than first level.

Pleeeaaassee help! Thanks guys!

Upvotes: 1

Views: 411

Answers (1)

Alnitak
Alnitak

Reputation: 340055

Your problem is here, inside the if (stat ...) branch:

readAllDirs(fullpath);

You need to pass the supplied callback again back into the recursion:

readAllDirs(fullpath, result);

Upvotes: 1

Related Questions