node.js fs.readdir recursive directory search

前端 未结 30 2067
醉酒成梦
醉酒成梦 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:26

    Because everyone should write his own, I made one.

    walk(dir, cb, endCb) cb(file) endCb(err | null)

    DIRTY

    module.exports = walk;
    
    function walk(dir, cb, endCb) {
      var fs = require('fs');
      var path = require('path');
    
      fs.readdir(dir, function(err, files) {
        if (err) {
          return endCb(err);
        }
    
        var pending = files.length;
        if (pending === 0) {
          endCb(null);
        }
        files.forEach(function(file) {
          fs.stat(path.join(dir, file), function(err, stats) {
            if (err) {
              return endCb(err)
            }
    
            if (stats.isDirectory()) {
              walk(path.join(dir, file), cb, function() {
                pending--;
                if (pending === 0) {
                  endCb(null);
                }
              });
            } else {
              cb(path.join(dir, file));
              pending--;
              if (pending === 0) {
                endCb(null);
              }
            }
          })
        });
    
      });
    }
    

提交回复
热议问题