find files by extension, *.html under a folder in nodejs

后端 未结 14 807
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 23:57

I\'d like to find all *.html files in src folder and all its sub folders using nodejs. What is the best way to do it?

var folder = \'/project1/src\';
var ex         


        
14条回答
  •  感情败类
    2020-12-08 00:20

    my two pence, using map in place of for-loop

    var path = require('path'), fs = require('fs');
    
    var findFiles = function(folder, pattern = /.*/, callback) {
      var flist = [];
    
      fs.readdirSync(folder).map(function(e){ 
        var fname = path.join(folder, e);
        var fstat = fs.lstatSync(fname);
        if (fstat.isDirectory()) {
          // don't want to produce a new array with concat
          Array.prototype.push.apply(flist, findFiles(fname, pattern, callback)); 
        } else {
          if (pattern.test(fname)) {
            flist.push(fname);
            if (callback) {
              callback(fname);
            }
          }
        }
      });
      return flist;
    };
    
    // HTML files   
    var html_files = findFiles(myPath, /\.html$/, function(o) { console.log('look what we have found : ' + o} );
    
    // All files
    var all_files = findFiles(myPath);
    

提交回复
热议问题