UNPKG

recursive-search

Version:

Recursively search a file in given directory from file name or RegExp

78 lines (73 loc) 1.96 kB
// Generated by CoffeeScript 1.8.0 var dive, fs, path; fs = require('fs'); path = require('path'); dive = require('dive'); module.exports = { recursiveSearchSync: function(filename, dir, options) { var f, matches; if (arguments.length !== 3) { options = { all: false }; } matches = []; f = (function(dir) { var i, list, next; list = fs.readdirSync(dir); i = 0; next = (function() { var condition, file, stat; file = list[i++]; if (!file) { return matches; } file = path.join(dir, file); stat = fs.statSync(file); if (stat && stat.isDirectory()) { f(file); return next(); } else { condition = (filename.constructor.name === "RegExp" ? path.basename(file).match(filename) : path.basename(file) === filename); if (condition || filename === '*') { if (options.all === false) { if (path.basename(file).charAt(0) !== '.') { matches.push(file); } } else { matches.push(file); } } return next(); } }); return next(); }); f(dir); return matches; }, recursiveSearch: function(filename, dir, options, callback, complete) { var matches; if (arguments.length !== 5) { complete = callback; callback = options; options = { all: false }; } matches = []; return dive(dir, options, function(err, file) { var condition; if (err) { return callback(err); } condition = (filename.constructor.name === "RegExp" ? path.basename(file).match(filename) : path.basename(file) === filename); if (condition || filename === '*') { matches.push(file); return callback(null, file); } }, function() { return complete(matches); }); } };