Created
November 9, 2014 10:33
-
-
Save felixzapata/aacb743a9bfd94e08932 to your computer and use it in GitHub Desktop.
node.js glob pattern for excluding multiple files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Walk directory, | |
list tree without regex excludes | |
http://stackoverflow.com/questions/23809897/node-js-glob-pattern-for-excluding-multiple-files | |
*/ | |
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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment