在nodejs中的文件夹下按扩展名*.html查找文件 [英] find files by extension, *.html under a folder in nodejs

查看:42
本文介绍了在nodejs中的文件夹下按扩展名*.html查找文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 nodejs 查找 src 文件夹及其所有子文件夹中的所有 *.html 文件.最好的方法是什么?

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 extension = 'html';
var cb = function(err, results) {
   // results is an array of the files with path relative to the folder
   console.log(results);

}
// This function is what I am looking for. It has to recursively traverse all sub folders. 
findFiles(folder, extension, cb);

我认为很多开发人员都应该拥有出色且经过测试的解决方案,并且使用它比自己编写一个更好.

I think a lot developers should have great and tested solution and it is better to use it than writing one myself.

推荐答案

node.js,递归简单函数:

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');

如果你想变得花哨,请添加 RegExp,并添加一个回调以使其通用.

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);
});

这篇关于在nodejs中的文件夹下按扩展名*.html查找文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆