index.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. var fs = require('fs'),
  2. path = require('path'),
  3. stat = fs.statSync,
  4. readdir = fs.readdirSync,
  5. dirname = path.dirname,
  6. basename = path.basename,
  7. extname = path.extname,
  8. sep = path.sep,
  9. dire = function (root, flat, ext) {
  10. var m = {};
  11. (flat ? direFlat : direNested)(m, root, [], ext);
  12. return m;
  13. },
  14. direNested = function (m, r, d, e) {
  15. var entries = readdir([r, d.join(sep)].join(sep));
  16. for (var i = 0; i < entries.length; ++i) {
  17. var p = [r, d.join(sep), entries[i]].join(sep);
  18. if (stat(p).isDirectory()) {
  19. var d1 = d.slice(0);
  20. d1.push(entries[i]);
  21. direNested(m, r, d1, e);
  22. } else {
  23. if (!e || extname(p) === e) {
  24. var m1 = m;
  25. for (var j = 0; j < d.length; ++j) {
  26. m1[d[j]] = m1[d[j]] || {};
  27. m1 = m1[d[j]];
  28. }
  29. m1[basename(entries[i], extname(entries[i]))] = require(path.resolve(p));
  30. }
  31. }
  32. }
  33. },
  34. direFlat = function (m, r, d, e) {
  35. var entries = readdir([r, d.join(sep)].join(sep));
  36. for (var i = 0; i < entries.length; ++i) {
  37. var p = [r, d.join(sep), entries[i]].join(sep);
  38. if (stat(p).isDirectory()) {
  39. var d1 = d.slice(0);
  40. d1.push(entries[i]);
  41. direFlat(m, r, d1, e);
  42. } else {
  43. if (!e || extname(p) === e) {
  44. var n = d.length ? [d.join(sep), basename(entries[i], extname(entries[i]))].join(sep)
  45. : basename(entries[i], extname(entries[i]));
  46. m[n] = require(path.resolve(p));
  47. }
  48. }
  49. }
  50. };
  51. module.exports = dire;