[英]node.js glob pattern for excluding multiple files
我正在使用 npm 模塊node-glob 。
此代碼段遞歸返回當前工作目錄中的所有文件。
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 。 我試圖用否定模式“!”排除這些文件但沒有運氣。 有沒有辦法僅通過使用模式來實現這一目標?
我想它不再是真實的,但我遇到了同樣的問題並找到了答案。
這可以僅使用glob
模塊來完成。 我們需要使用選項作為glob
函數的第二個參數
glob('pattern', {options}, cb)
有一個options.ignore
模式可以滿足您的需求。
var glob = require('glob');
glob("**/*",{"ignore":['index.html', 'js', 'js/app.js', 'js/lib.js']}, function (err, files) {
console.log(files);
})
您可以使用node-globule :
var globule = require('globule');
var result = globule.find(['**/*', '!index.html', '!js/lib.js']);
console.log(result);
或者沒有外部依賴:
/**
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);
});
這是我為我的項目寫的:
var glob = require('glob');
var minimatch = require("minimatch");
function globArray(patterns, options) {
var i, list = [];
if (!Array.isArray(patterns)) {
patterns = [patterns];
}
patterns.forEach(function (pattern) {
if (pattern[0] === "!") {
i = list.length-1;
while( i > -1) {
if (!minimatch(list[i], pattern)) {
list.splice(i,1);
}
i--;
}
}
else {
var newList = glob.sync(pattern, options);
newList.forEach(function(item){
if (list.indexOf(item)===-1) {
list.push(item);
}
});
}
});
return list;
}
並像這樣調用它(使用數組):
var paths = globArray(["**/*.css","**/*.js","!**/one.js"], {cwd: srcPath});
或者這個(使用單個字符串):
var paths = globArray("**/*.js", {cwd: srcPath});
gulp 的示例示例:
gulp.task('task_scripts', function(done){
glob("./assets/**/*.js", function (er, files) {
gulp.src(files)
.pipe(gulp.dest('./public/js/'))
.on('end', done);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.