通过扩展名查找文件,*.html在nodejs的文件夹下

编程入门 行业动态 更新时间:2024-10-21 06:30:11
本文介绍了通过扩展名查找文件,*.html在nodejs的文件夹下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用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); });

更多推荐

通过扩展名查找文件,*.html在nodejs的文件夹下

本文发布于:2023-11-28 16:48:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643191.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:扩展名   文件夹   文件   html   nodejs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!