【问题标题】:node.js glob pattern for excluding multiple files用于排除多个文件的 node.js glob 模式
【发布时间】:2021-03-10 14:17:25
【问题描述】:

我正在使用 npm 模块node-glob

这个 sn-p 递归返回当前工作目录中的所有文件。

var glob = require('glob');
glob('**/*', function(err, files) {
    console.log(files);
});

样本输出:

[ 'index.html', 'js', 'js/app.js', 'js/lib.js' ]

我想排除 index.htmljs/lib.js。 我试图用否定模式 '!' 排除这些文件,但没有运气。 有没有办法只通过使用模式来实现这一点?

【问题讨论】:

  • 使用ignore 选项。 ! 在 node-glob 模式中已弃用。

标签: node.js glob


【解决方案1】:

我想这不再是实际的了,但我遇到了同样的问题并找到了答案。

这只能使用glob 模块来完成。 我们需要使用options作为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-glob 的库。我无法使用任何其他解决方案。
  • 知道为什么{"ignore": ['*dex*']} 不忽略index.html
【解决方案2】:

查看globby,它几乎是glob,支持多种模式和Promise API:

const globby = require('globby');

globby(['**/*', '!index.html', '!js/lib.js']).then(paths => {
    console.log(paths);
});

【讨论】:

  • 这几乎只是支持多种模式的 glob(不是 node-glob,它是一个死胡同,没有下载没有自述文件模块)
  • globby 基本上是在很棒的 glob 库之上的香草......不是那么有用。
【解决方案3】:

您可以为此使用node-globule

var globule = require('globule');
var result = globule.find(['**/*', '!index.html', '!js/lib.js']);
console.log(result);

【讨论】:

    【解决方案4】:

    或者没有外部依赖:

    /**
        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);
    });
    

    【讨论】:

    • 我当然喜欢避免不必要的外部依赖的想法,但是这个 sn-p 重新定义了我的“人们永远不应该写的更糟糕的事情”的规模。对于新手来说,如果你不确定如何正确地做这件事,那么使用外部依赖。
    【解决方案5】:

    这是我为我的项目写的:

    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});
    

    【讨论】:

    • 我明白了:Argument of type 'any' is not assignable to parameter of type 'never
    • 你在使用 TypeScript 吗?是这条线的错误吗? patterns = [patterns];你能提供更多关于错误信息的信息吗?你的帖子好像被删了。
    • 是的,使用 typeScript 2.5.2,if (list.indexOf(item)===-1) { 错误出现在 itemlist.push(item);
    • 对不起,我不使用 TypeScript。有没有人知道为什么@An-droid id 会出现这个错误?
    【解决方案6】:

    gulp 示例:

    gulp.task('task_scripts', function(done){
    
        glob("./assets/**/*.js", function (er, files) {
            gulp.src(files)
                .pipe(gulp.dest('./public/js/'))
                .on('end', done);
        });
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 2017-12-09
      • 2013-03-11
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 1970-01-01
      相关资源
      最近更新 更多