node.js glob模式,用于排除多个文件

ke_*_*_wa 36 glob node.js

我正在使用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.htmlJS/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)

  • 知道为什么 `{"ignore": ['*dex*']}` 不忽略 `index.html` 吗? (3认同)

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)

  • 我当然喜欢避免不必要的外部依赖的想法,但这个片段重新定义了我的“人们永远不应该写的更糟糕的东西”的范围。对于新手来说,如果您不确定如何正确执行该操作,请使用外部依赖项。 (8认同)