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

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

    I have looked at the above answers and have mixed together this version which works for me:

    function getFilesFromPath(path, extension) {
        let files = fs.readdirSync( path );
        return files.filter( file => file.match(new RegExp(`.*\.(${extension})`, 'ig')));
    }
    
    console.log(getFilesFromPath("./testdata", ".txt"));
    

    This test will return an array of filenames from the files found in the folder at the path ./testdata. Working on node version 8.11.3.

    0 讨论(0)
  • 2020-12-08 00:35

    node.js, recursive simple function:

    var path = require('path'), fs=require('fs');
    
    function fromDir(startPath,filter){
    
        //console.log('Starting from dir '+startPath+'/');
    
        if (!fs.existsSync(startPath)){
            console.log("no dir ",startPath);
            return;
        }
    
        var files=fs.readdirSync(startPath);
        for(var i=0;i<files.length;i++){
            var filename=path.join(startPath,files[i]);
            var stat = fs.lstatSync(filename);
            if (stat.isDirectory()){
                fromDir(filename,filter); //recurse
            }
            else if (filename.indexOf(filter)>=0) {
                console.log('-- found: ',filename);
            };
        };
    };
    
    fromDir('../LiteScript','.html');
    

    add RegExp if you want to get fancy, and a callback to make it generic.

    var path = require('path'), fs=require('fs');
    
    function fromDir(startPath,filter,callback){
    
        //console.log('Starting from dir '+startPath+'/');
    
        if (!fs.existsSync(startPath)){
            console.log("no dir ",startPath);
            return;
        }
    
        var files=fs.readdirSync(startPath);
        for(var i=0;i<files.length;i++){
            var filename=path.join(startPath,files[i]);
            var stat = fs.lstatSync(filename);
            if (stat.isDirectory()){
                fromDir(filename,filter,callback); //recurse
            }
            else if (filter.test(filename)) callback(filename);
        };
    };
    
    fromDir('../LiteScript',/\.html$/,function(filename){
        console.log('-- found: ',filename);
    });
    
    0 讨论(0)
  • 2020-12-08 00:35

    i like using the glob package:

    const glob = require('glob');
    
    glob(__dirname + '/**/*.html', {}, (err, files)=>{
      console.log(files)
    })
    
    0 讨论(0)
  • 2020-12-08 00:35

    Install

    you can install this package walk-sync by

    yarn add walk-sync
    

    Usage

    const walkSync = require("walk-sync");
    const paths = walkSync("./project1/src", {globs: ["**/*.html"]});
    console.log(paths);   //all html file path array
    
    0 讨论(0)
  • 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<files.length;i++){
            var filename=path.join(startPath,files[i]);
            var stat = fs.lstatSync(filename);
            if (stat.isDirectory()){
                results = results.concat(findFilesInDir(filename,filter)); //recurse
            }
            else if (filename.indexOf(filter)>=0) {
                console.log('-- found: ',filename);
                results.push(filename);
            }
        }
        return results;
    }
    
    module.exports = findFilesInDir;
    
    0 讨论(0)
  • 2020-12-08 00:37

    You can use Filehound to do this.

    For example: find all .html files in /tmp:

    const Filehound = require('filehound');
    
    Filehound.create()
      .ext('html')
      .paths("/tmp")
      .find((err, htmlFiles) => {
        if (err) return console.error("handle err", err);
    
        console.log(htmlFiles);
    });
    

    For further information (and examples), check out the docs: https://github.com/nspragg/filehound

    Disclaimer: I'm the author.

    0 讨论(0)
提交回复
热议问题