本文介绍了通过扩展名查找文件,*.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的文件夹下
发布评论