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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23809897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:22:31  来源:igfitidea点击:

node.js glob pattern for excluding multiple files

node.jsglob

提问by ke_wa

I'm using the npm module node-glob.

我正在使用 npm 模块node-glob

This snippet returns recursively all files in the current working directory.

此代码段递归返回当前工作目录中的所有文件。

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

sample output:

示例输出:

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

I want to exclude index.htmland 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?

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

采纳答案by Koji

Or without an external dependency:

或者没有外部依赖:

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

回答by Sergei Panfilov

I suppose it's not actual anymore but i got stuck with the same question and found an answer.

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

This can be done using only npm globmodule. We need to use optionsas a second parameter to globfunction

这可以仅使用npm glob模块来完成。我们需要使用选项作为第二个参数来glob运行

glob('pattern', {options}, cb)

There is an options.ignorepattern for your needs.

有一种options.ignore模式可以满足您的需求。

var glob = require('glob');

glob("**/*",{"ignore":['index.html', 'js', 'js/app.js', 'js/lib.js']}, function (err, files) {
  console.log(files);
})

回答by Sindre Sorhus

Check out globby, which is pretty much globwith support for multiple patterns and a Promise API:

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

const globby = require('globby');

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

回答by stefanbuck

You can use node-globulefor that:

您可以使用node-globule

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

回答by Intervalia

Here is what I wrote for my project:

这是我为我的项目写的:

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

And call it like this (Using an array):

并像这样调用它(使用数组):

var paths = globArray(["**/*.css","**/*.js","!**/one.js"], {cwd: srcPath});

or this (Using a single string):

或者这个(使用单个字符串):

var paths = globArray("**/*.js", {cwd: srcPath});

回答by Ivan Ferrer

A samples example with gulp:

gulp 的示例示例:

gulp.task('task_scripts', function(done){

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

});