node.js fs.readdir recursive directory search

前端 未结 30 1515
醉酒成梦
醉酒成梦 2020-11-22 15:55

Any ideas on an async directory search using fs.readdir? I realise that we could introduce recursion and call the read directory function with the next directory to read, bu

30条回答
  •  囚心锁ツ
    2020-11-22 16:24

    I loved the answer from chjj above and would not have been able to create my version of the parallel loop without that start.

    var fs = require("fs");
    
    var tree = function(dir, done) {
      var results = {
            "path": dir
            ,"children": []
          };
      fs.readdir(dir, function(err, list) {
        if (err) { return done(err); }
        var pending = list.length;
        if (!pending) { return done(null, results); }
        list.forEach(function(file) {
          fs.stat(dir + '/' + file, function(err, stat) {
            if (stat && stat.isDirectory()) {
              tree(dir + '/' + file, function(err, res) {
                results.children.push(res);
                if (!--pending){ done(null, results); }
              });
            } else {
              results.children.push({"path": dir + "/" + file});
              if (!--pending) { done(null, results); }
            }
          });
        });
      });
    };
    
    module.exports = tree;
    

    I created a Gist as well. Comments welcome. I am still starting out in the NodeJS realm so that is one way I hope to learn more.

提交回复
热议问题