在 nodejs 中的文件夹下按扩展名查找文件 *.html
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25460574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
find files by extension, *.html under a folder in nodejs
提问by Nicolas S.Xu
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?
我想使用 nodejs 在 src 文件夹及其所有子文件夹中找到所有 *.html 文件。最好的方法是什么?
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.
我认为很多开发人员都应该拥有出色且经过测试的解决方案,并且使用它比自己编写一个更好。
回答by Lucio M. Tato
node.js, recursive simple function:
node.js,递归简单函数:
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.
如果你想要花哨,请添加 RegExp,并添加一个回调以使其通用。
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);
});
回答by David Cheung
回答by Master James
What, hang on?! ... Okay ya, maybe this makes more sense to someones else too.
什么,坚持?!...好吧,也许这对其他人也更有意义。
[nodejs 7mind you]
[ nodejs 7 请注意]
fs = import('fs');
let dirCont = fs.readdirSync( dir );
let files = dirCont.filter( function( elm ) {return elm.match(/.*\.(htm?html)/ig);});
Do whatever with regex make it an argument you set in the function with a default etc.
使用正则表达式执行任何操作,使其成为您在函数中使用默认值等设置的参数。
回答by Nicolas S.Xu
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.
基于Lucio的代码,我做了一个模块。它将返回一个带有特定扩展名的所有文件。把它贴在这里以防有人需要它。
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;
回答by nickool
You can use Filehoundto do this.
您可以使用Filehound来执行此操作。
For example: find all .html files in /tmp:
例如:在 /tmp 中查找所有 .html 文件:
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
有关更多信息(和示例),请查看文档:https: //github.com/nspragg/filehound
Disclaimer: I'm the author.
免责声明:我是作者。
回答by Netsi1964
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.
此测试将从 path 文件夹中找到的文件中返回文件名数组./testdata。在节点版本 8.11.3 上工作。
回答by Nikhil
The following code does a recursive search inside ./ (change it appropriately) and returns an array of absolute file names ending with .html
以下代码在 ./ 中进行递归搜索(适当更改)并返回以 .html 结尾的绝对文件名数组
var fs = require('fs');
var path = require('path');
var searchRecursive = function(dir, pattern) {
// This is where we store pattern matches of all files inside the directory
var results = [];
// Read contents of directory
fs.readdirSync(dir).forEach(function (dirInner) {
// Obtain absolute path
dirInner = path.resolve(dir, dirInner);
// Get stats to determine if path is a directory or a file
var stat = fs.statSync(dirInner);
// If path is a directory, scan it and combine results
if (stat.isDirectory()) {
results = results.concat(searchRecursive(dirInner, pattern));
}
// If path is a file and ends with pattern then push it onto results
if (stat.isFile() && dirInner.endsWith(pattern)) {
results.push(dirInner);
}
});
return results;
};
var files = searchRecursive('./', '.html'); // replace dir and pattern
// as you seem fit
console.log(files);
回答by Emil Condrea
You can use OS help for this. Here is a cross-platform solution:
为此,您可以使用操作系统帮助。这是一个跨平台的解决方案:
1. The bellow function uses lsand dirand does not search recursively but it has relative paths
1.波纹管函数使用lsanddir和,不递归搜索但有相对路径
var exec = require('child_process').exec;
function findFiles(folder,extension,cb){
var command = "";
if(/^win/.test(process.platform)){
command = "dir /B "+folder+"\*."+extension;
}else{
command = "ls -1 "+folder+"/*."+extension;
}
exec(command,function(err,stdout,stderr){
if(err)
return cb(err,null);
//get rid of \r from windows
stdout = stdout.replace(/\r/g,"");
var files = stdout.split("\n");
//remove last entry because it is empty
files.splice(-1,1);
cb(err,files);
});
}
findFiles("folderName","html",function(err,files){
console.log("files:",files);
})
2. The bellow function uses findand dir, searches recursively but on windows it has absolute paths
2. 波纹管函数使用findand dir,递归搜索,但在 windows 上它有绝对路径
var exec = require('child_process').exec;
function findFiles(folder,extension,cb){
var command = "";
if(/^win/.test(process.platform)){
command = "dir /B /s "+folder+"\*."+extension;
}else{
command = 'find '+folder+' -name "*.'+extension+'"'
}
exec(command,function(err,stdout,stderr){
if(err)
return cb(err,null);
//get rid of \r from windows
stdout = stdout.replace(/\r/g,"");
var files = stdout.split("\n");
//remove last entry because it is empty
files.splice(-1,1);
cb(err,files);
});
}
findFiles("folder","html",function(err,files){
console.log("files:",files);
})
回答by Akash Babu
Take a look into file-regex
看看文件正则表达式
let findFiles = require('file-regex')
let pattern = '\.js'
findFiles(__dirname, pattern, (err, files) => {
console.log(files);
})
This above snippet would print all the jsfiles in the current directory.
上面的代码段将打印js当前目录中的所有文件。
回答by jset74
my two pence, using map in place of for-loop
我的两便士,使用地图代替 for 循环
var path = require('path'), fs = require('fs');
var findFiles = function(folder, pattern = /.*/, callback) {
var flist = [];
fs.readdirSync(folder).map(function(e){
var fname = path.join(folder, e);
var fstat = fs.lstatSync(fname);
if (fstat.isDirectory()) {
// don't want to produce a new array with concat
Array.prototype.push.apply(flist, findFiles(fname, pattern, callback));
} else {
if (pattern.test(fname)) {
flist.push(fname);
if (callback) {
callback(fname);
}
}
}
});
return flist;
};
// HTML files
var html_files = findFiles(myPath, /\.html$/, function(o) { console.log('look what we have found : ' + o} );
// All files
var all_files = findFiles(myPath);

