我正在使用npm模块node-glob.
此代码段以递归方式返回当前工作目录中的所有文件.
var glob = require('glob');
glob('**/*', function(err, files) {
console.log(files);
});
Run Code Online (Sandbox Code Playgroud)
样本输出:
[ 'index.html', 'js', 'js/app.js', 'js/lib.js' ]
Run Code Online (Sandbox Code Playgroud)
我想排除的index.html和JS/lib.js.我试图用负面模式排除这些文件'!' 但没有运气.有没有办法只通过使用模式来实现这一目标?
Ser*_*lov 52
我想这不再是实际的了,但我遇到了同样的问题并找到了答案.
这可以仅使用npm glob
模块完成.我们需要使用选项作为第二个参数来glob
运行
glob('pattern', {options}, cb)
Run Code Online (Sandbox Code Playgroud)
有一种options.ignore
模式可以满足您的需求.
var glob = require('glob');
glob("**/*",{"ignore":['index.html', 'js', 'js/app.js', 'js/lib.js']}, function (err, files) {
console.log(files);
})
Run Code Online (Sandbox Code Playgroud)
Sin*_*hus 43
退房globby
,这几乎glob
支持多种模式和Promise API:
const globby = require('globby');
globby(['**/*', '!index.html', '!js/lib.js']).then(paths => {
console.log(paths);
});
Run Code Online (Sandbox Code Playgroud)
ste*_*uck 17
您可以使用node-globule:
var globule = require('globule');
var result = globule.find(['**/*', '!index.html', '!js/lib.js']);
console.log(result);
Run Code Online (Sandbox Code Playgroud)
小智 3
或者没有外部依赖:
/**
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);
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
56106 次 |
最近记录: |