node.js fs.readdir recursive directory search

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

    Whoever wants a synchronous alternative to the accepted answer (I know I did):

    var fs = require('fs');
    var path = require('path');
    var walk = function(dir) {
        let results = [], err = null, list;
        try {
            list = fs.readdirSync(dir)
        } catch(e) {
            err = e.toString();
        }
        if (err) return err;
        var i = 0;
        return (function next() {
            var file = list[i++];
    
            if(!file) return results;
            file = path.resolve(dir, file);
            let stat = fs.statSync(file);
            if (stat && stat.isDirectory()) {
              let res = walk(file);
              results = results.concat(res);
              return next();
            } else {
              results.push(file);
               return next();
            }
    
        })();
    
    };
    
    console.log(
        walk("./")
    )
    

提交回复
热议问题