Skip to content

Instantly share code, notes, and snippets.

@atomAltera
Last active August 29, 2015 13:56
Show Gist options
  • Save atomAltera/9161645 to your computer and use it in GitHub Desktop.
Save atomAltera/9161645 to your computer and use it in GitHub Desktop.
Node.js async text files search
var fs = require('fs');
var mime = require('mime');
function file_type_search(path, mime_match, callback_all, callback_each) {
var file_list = [];
var level = 0;
if (typeof callback_all !== 'function') callback_all = false;
if (typeof callback_each !== 'function') callback_each = false;
function enter() {
level += 1;
}
function leave() {
level -= 1;
if ((level == 0) && callback_all) callback_all(file_list);
}
function scan_directory(path, file_list) {
path = (path.charAt(path.length - 1) == '/') ? path : path + '/';
fs.readdir(path, function (err, files) {
if (err) {
console.error(err.message);
leave();
return;
}
for (var index in files) {
process_directory_entry(path + files[index], file_list);
}
leave();
});
}
function process_directory_entry(path, file_list) {
enter();
fs.stat(path, function (err, stats) {
if (err) {
console.error(err.message);
leave();
return
}
if (stats.isDirectory()) {
scan_directory(path, file_list);
} else {
if (stats.isFile) {
if (mime.lookup(path).match(mime_match)) {
if (callback_all) file_list.push(path);
if (callback_each) callback_each(path);
}
}
leave();
}
});
}
process_directory_entry(path, file_list);
}
module.exports = file_type_search;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment