用于排除多个文件的node.js glob模式 [英] node.js glob pattern for excluding multiple files
本文介绍了用于排除多个文件的node.js glob模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用npm模块 node-glob .
I'm using the npm module node-glob.
此代码段递归返回当前工作目录中的所有文件.
This snippet returns recursively all files in the current working directory.
var glob = require('glob');
glob('**/*', function(err, files) {
console.log(files);
});
示例输出:
[ 'index.html', 'js', 'js/app.js', 'js/lib.js' ]
我要排除 index.html 和 js/lib.js . 我试图排除这些文件的方式为'!',但没有运气. 有没有一种方法可以仅通过使用模式来实现?
I want to exclude index.html and js/lib.js. I tried to exclude these files with negative pattern '!' but without luck. Is there a way to achieve this only by using a pattern?
推荐答案
或者没有外部依赖项:
/**
Walk directory,
list tree without regex excludes
*/
var fs = require('fs');
var path = require('path');
var walk = function (dir, regExcludes, done) {
var results = [];
fs.readdir(dir, function (err, list) {
if (err) return done(err);
var pending = list.length;
if (!pending) return done(null, results);
list.forEach(function (file) {
file = path.join(dir, file);
var excluded = false;
var len = regExcludes.length;
var i = 0;
for (; i < len; i++) {
if (file.match(regExcludes[i])) {
excluded = true;
}
}
// Add if not in regExcludes
if(excluded === false) {
results.push(file);
// Check if its a folder
fs.stat(file, function (err, stat) {
if (stat && stat.isDirectory()) {
// If it is, walk again
walk(file, regExcludes, function (err, res) {
results = results.concat(res);
if (!--pending) { done(null, results); }
});
} else {
if (!--pending) { done(null, results); }
}
});
} else {
if (!--pending) { done(null, results); }
}
});
});
};
var regExcludes = [/index\.html/, /js\/lib\.js/, /node_modules/];
walk('.', regExcludes, function(err, results) {
if (err) {
throw err;
}
console.log(results);
});
这篇关于用于排除多个文件的node.js glob模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文