node.js glob pattern for excluding multiple files

后端 未结 6 1250
情话喂你
情话喂你 2020-12-24 10:56

I\'m using the npm module node-glob.

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

var glob = require(\'glob\');
glob(         


        
6条回答
  •  鱼传尺愫
    2020-12-24 11:44

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

提交回复
热议问题