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

问题描述 投票:0回答:7

我正在使用 npm 模块 node-glob

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

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

示例输出:

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

我想排除 index.htmljs/lib.js。 我尝试排除这些具有负模式 '!' 的文件,但没有成功。 有没有一种方法可以仅通过使用模式来实现这一点?

node.js glob
7个回答
74
投票

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

这可以仅使用

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

47
投票

查看

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

const globby = require('globby');

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

18
投票

您可以使用 node-globule 来实现:

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

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

3
投票

这是我为我的项目写的内容:

var glob = require('glob');
var minimatch = require("minimatch");

function globArray(patterns, options) {
  var i, list = [];
  if (!Array.isArray(patterns)) {
    patterns = [patterns];
  }

  patterns.forEach(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(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});

1
投票

带有 gulp 的示例:

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

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

});

0
投票

截至 2024 年更新

Node.js 22 或更高版本内置了

glob
方法。所以你不再需要使用像
node-glob
这样的外部包了。

Sergei Panfilov 答案可以这样重写,无需外部依赖:

import { glob } from 'node:fs/promises';

for await (const entry of glob('**/*.js', { ignore: ['index.html', 'js', 'js/app.js', 'js/lib.js'] })) {
  console.log(entry);
}
© www.soinside.com 2019 - 2024. All rights reserved.