Skip to content

Instantly share code, notes, and snippets.

@allanlei
Created January 18, 2012 21:34
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 allanlei/1635849 to your computer and use it in GitHub Desktop.
Save allanlei/1635849 to your computer and use it in GitHub Desktop.
Coffeescript that finds files with extensions using the async library
var findFilesWithExtension,
_this = this;
findFilesWithExtension = function(dir, extensions, callback) {
var directories, files;
files = [];
directories = [dir];
return async.whilst(function() {
return directories.length > 0;
}, function(whilstCallback) {
var directory;
directory = directories.pop();
return fs.readdir(directory, function(err, fileList) {
var f, stats, _i, _len;
for (_i = 0, _len = fileList.length; _i < _len; _i++) {
f = fileList[_i];
f = directory + '/' + f;
stats = fs.statSync(f);
if (stats.isFile()) {
files.push(f);
} else if (stats.isDirectory()) {
directories.push(f);
}
}
return whilstCallback();
});
}, function(err) {
if (err) throw err;
return async.filter(files, function(file, filterCallback) {
return async.detect(extensions, function(extension, detectCallback) {
return detectCallback(~file.indexOf(extension));
}, function(result) {
return filterCallback(result);
});
}, function(results) {
return callback(results);
});
});
};
findFilesWithExtension = (dir, extensions, callback) =>
files = []
directories = [dir]
async.whilst () =>
directories.length > 0
, (whilstCallback) =>
directory = directories.pop()
fs.readdir directory, (err, fileList) =>
for f in fileList
f = directory + '/' + f
stats = fs.statSync f
if stats.isFile()
files.push f
else if stats.isDirectory()
directories.push f
whilstCallback()
, (err) =>
if err
throw err
async.filter files, (file, filterCallback) =>
async.detect extensions, (extension, detectCallback) =>
detectCallback ~file.indexOf extension
, (result) =>
filterCallback result
, (results) =>
callback(results)
findFilesWithExtension "static", [".js"], (files) =>
# Do something with the filtered files
console.log files
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment