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

后端 未结 14 799
隐瞒了意图╮
隐瞒了意图╮ 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:22

    The following code does a recursive search inside ./ (change it appropriately) and returns an array of absolute file names ending with .html

    var fs = require('fs');
    var path = require('path');
    
    var searchRecursive = function(dir, pattern) {
      // This is where we store pattern matches of all files inside the directory
      var results = [];
    
      // Read contents of directory
      fs.readdirSync(dir).forEach(function (dirInner) {
        // Obtain absolute path
        dirInner = path.resolve(dir, dirInner);
    
        // Get stats to determine if path is a directory or a file
        var stat = fs.statSync(dirInner);
    
        // If path is a directory, scan it and combine results
        if (stat.isDirectory()) {
          results = results.concat(searchRecursive(dirInner, pattern));
        }
    
        // If path is a file and ends with pattern then push it onto results
        if (stat.isFile() && dirInner.endsWith(pattern)) {
          results.push(dirInner);
        }
      });
    
      return results;
    };
    
    var files = searchRecursive('./', '.html'); // replace dir and pattern
                                                    // as you seem fit
    
    console.log(files);
    

提交回复
热议问题