node.js fs.readdir recursive directory search

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

    Another nice npm package is glob.

    npm install glob

    It is very powerful and should cover all your recursing needs.

    Edit:

    I actually wasn't perfectly happy with glob, so I created readdirp.

    I'm very confident that its API makes finding files and directories recursively and applying specific filters very easy.

    Read through its documentation to get a better idea of what it does and install via:

    npm install readdirp

    0 讨论(0)
  • 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("./")
    )
    
    0 讨论(0)
  • 2020-11-22 16:18

    I've coded this recently, and thought it would make sense to share this here. The code makes use of the async library.

    var fs = require('fs');
    var async = require('async');
    
    var scan = function(dir, suffix, callback) {
      fs.readdir(dir, function(err, files) {
        var returnFiles = [];
        async.each(files, function(file, next) {
          var filePath = dir + '/' + file;
          fs.stat(filePath, function(err, stat) {
            if (err) {
              return next(err);
            }
            if (stat.isDirectory()) {
              scan(filePath, suffix, function(err, results) {
                if (err) {
                  return next(err);
                }
                returnFiles = returnFiles.concat(results);
                next();
              })
            }
            else if (stat.isFile()) {
              if (file.indexOf(suffix, file.length - suffix.length) !== -1) {
                returnFiles.push(filePath);
              }
              next();
            }
          });
        }, function(err) {
          callback(err, returnFiles);
        });
      });
    };
    

    You can use it like this:

    scan('/some/dir', '.ext', function(err, files) {
      // Do something with files that ends in '.ext'.
      console.log(files);
    });
    
    0 讨论(0)
  • 2020-11-22 16:18

    The recursive-readdir module has this functionality.

    0 讨论(0)
  • 2020-11-22 16:18

    I must add the Promise-based sander library to the list.

     var sander = require('sander');
     sander.lsr(directory).then( filenames => { console.log(filenames) } );
    
    0 讨论(0)
  • 2020-11-22 16:19

    With Recursion

    var fs = require('fs')
    var path = process.cwd()
    var files = []
    
    var getFiles = function(path, files){
        fs.readdirSync(path).forEach(function(file){
            var subpath = path + '/' + file;
            if(fs.lstatSync(subpath).isDirectory()){
                getFiles(subpath, files);
            } else {
                files.push(path + '/' + file);
            }
        });     
    }
    

    Calling

    getFiles(path, files)
    console.log(files) // will log all files in directory
    
    0 讨论(0)
提交回复
热议问题