index.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. var fs = require("fs");
  2. var p = require("path");
  3. var minimatch = require("minimatch");
  4. function patternMatcher(pattern) {
  5. return function(path, stats) {
  6. var minimatcher = new minimatch.Minimatch(pattern, { matchBase: true });
  7. return (!minimatcher.negate || stats.isFile()) && minimatcher.match(path);
  8. };
  9. }
  10. function toMatcherFunction(ignoreEntry) {
  11. if (typeof ignoreEntry == "function") {
  12. return ignoreEntry;
  13. } else {
  14. return patternMatcher(ignoreEntry);
  15. }
  16. }
  17. function readdir(path, ignores, callback) {
  18. if (typeof ignores == "function") {
  19. callback = ignores;
  20. ignores = [];
  21. }
  22. if (!callback) {
  23. return new Promise(function(resolve, reject) {
  24. readdir(path, ignores || [], function(err, data) {
  25. if (err) {
  26. reject(err);
  27. } else {
  28. resolve(data);
  29. }
  30. });
  31. });
  32. }
  33. ignores = ignores.map(toMatcherFunction);
  34. var list = [];
  35. fs.readdir(path, function(err, files) {
  36. if (err) {
  37. return callback(err);
  38. }
  39. var pending = files.length;
  40. if (!pending) {
  41. // we are done, woop woop
  42. return callback(null, list);
  43. }
  44. files.forEach(function(file) {
  45. var filePath = p.join(path, file);
  46. fs.stat(filePath, function(_err, stats) {
  47. if (_err) {
  48. return callback(_err);
  49. }
  50. if (
  51. ignores.some(function(matcher) {
  52. return matcher(filePath, stats);
  53. })
  54. ) {
  55. pending -= 1;
  56. if (!pending) {
  57. return callback(null, list);
  58. }
  59. return null;
  60. }
  61. if (stats.isDirectory()) {
  62. readdir(filePath, ignores, function(__err, res) {
  63. if (__err) {
  64. return callback(__err);
  65. }
  66. list = list.concat(res);
  67. pending -= 1;
  68. if (!pending) {
  69. return callback(null, list);
  70. }
  71. });
  72. } else {
  73. list.push(filePath);
  74. pending -= 1;
  75. if (!pending) {
  76. return callback(null, list);
  77. }
  78. }
  79. });
  80. });
  81. });
  82. }
  83. module.exports = readdir;