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

时间:2021-12-29 19:52:01

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.html and 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.html和js / lib.js。我试图用负面模式'!'排除这些文件但没有运气。有没有办法通过使用模式来实现这一目标?

5 个解决方案

#1


-4  

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

#2


32  

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

查看globby,它非常支持多种模式和Promise API:

const globby = require('globby');

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

#3


29  

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 glob module. We need to use options as a second parameter to glob function

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

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

There is an options.ignore pattern 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);
})

#4


17  

You can use node-globule for that:

您可以使用node-globule:

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

#5


2  

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

#1


-4  

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

#2


32  

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

查看globby,它非常支持多种模式和Promise API:

const globby = require('globby');

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

#3


29  

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 glob module. We need to use options as a second parameter to glob function

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

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

There is an options.ignore pattern 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);
})

#4


17  

You can use node-globule for that:

您可以使用node-globule:

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

#5


2  

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