Last active
August 29, 2015 13:57
-
-
Save jonschlinkert/9721838 to your computer and use it in GitHub Desktop.
This file contains 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
var fs = require('fs'); | |
var path = require('path'); | |
var cleanPath = function(filepath) { | |
filepath = path.relative(process.cwd(), filepath); | |
return filepath.replace(/\\/g, '/'); | |
}; | |
function lookupFiles(dir, recursive) { | |
recursive = recursive || true; | |
var files = []; | |
var stat = fs.statSync(dir); | |
if (stat.isFile()) { | |
return dir; | |
} | |
fs.readdirSync(dir).forEach(function (filepath) { | |
filepath = path.resolve(path.join(dir, filepath)); | |
var stat = fs.statSync(filepath); | |
if (stat.isDirectory()) { | |
if (recursive === true) { | |
files = files.concat(lookupFiles(filepath, recursive)); | |
} | |
return; | |
} | |
if (!stat.isFile()) { | |
return; | |
} | |
files.push(filepath); | |
}); | |
return files; | |
} | |
// var result = lookupFiles('.'); | |
// console.log(result); | |
function filter(dir, options) { | |
options = options || {}; | |
var matches = []; | |
var i = 0; | |
lookupFiles(dir).map(function (item) { | |
i++; | |
matches.push(item); | |
if (options.basename) { | |
var filename = path.basename(item); | |
options.basename.forEach(function (filepath) { | |
if (filename.indexOf(filepath) !== -1) { | |
matches.splice(filename.indexOf(i)) | |
} | |
}); | |
} | |
if (options.dirname) { | |
var dir = path.dirname(item); | |
options.dirname.forEach(function (dirpath) { | |
if (dir.indexOf(dirpath) !== -1) { | |
matches.splice(dir.indexOf(i)) | |
} | |
}); | |
} | |
}); | |
return matches; | |
} | |
var results = filter('.', { | |
basename: ['js', 'md'], | |
dirname: ['node_modules'] | |
}).map(cleanPath); | |
console.log(results); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment