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

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

    Based on Lucio's code, I made a module. It will return an away with all the files with specific extensions under the one. Just post it here in case anybody needs it.

    var path = require('path'), 
        fs   = require('fs');
    
    
    /**
     * Find all files recursively in specific folder with specific extension, e.g:
     * findFilesInDir('./project/src', '.html') ==> ['./project/src/a.html','./project/src/build/index.html']
     * @param  {String} startPath    Path relative to this file or other file which requires this files
     * @param  {String} filter       Extension name, e.g: '.html'
     * @return {Array}               Result files with path string in an array
     */
    function findFilesInDir(startPath,filter){
    
        var results = [];
    
        if (!fs.existsSync(startPath)){
            console.log("no dir ",startPath);
            return;
        }
    
        var files=fs.readdirSync(startPath);
        for(var i=0;i=0) {
                console.log('-- found: ',filename);
                results.push(filename);
            }
        }
        return results;
    }
    
    module.exports = findFilesInDir;
    

提交回复
热议问题