Skip to content

Instantly share code, notes, and snippets.

@jonschlinkert
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonschlinkert/9721838 to your computer and use it in GitHub Desktop.
Save jonschlinkert/9721838 to your computer and use it in GitHub Desktop.
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