index.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. var FS = require('fs');
  2. var Path = require('path');
  3. module.exports = function (dir, basenames) {
  4. var requires = {};
  5. if (arguments.length === 2) {
  6. // if basenames argument is passed, explicitly include those files
  7. basenames.forEach(function (basename) {
  8. var filepath = Path.resolve(Path.join(dir, basename));
  9. requires[basename] = require(filepath);
  10. });
  11. } else if (arguments.length === 1) {
  12. // if basenames arguments isn't passed, require all javascript
  13. // files (except for those prefixed with _) and all directories
  14. var files = FS.readdirSync(dir);
  15. // sort files in lowercase alpha for linux
  16. files.sort(function (a,b) {
  17. a = a.toLowerCase();
  18. b = b.toLowerCase();
  19. if (a < b) {
  20. return -1;
  21. } else if (b < a) {
  22. return 1;
  23. } else {
  24. return 0;
  25. }
  26. });
  27. files.forEach(function (filename) {
  28. // ignore index.js and files prefixed with underscore and
  29. if ((filename === 'index.js') || (filename[0] === '_') || (filename[0] === '.')) {
  30. return;
  31. }
  32. var filepath = Path.resolve(Path.join(dir, filename));
  33. var ext = Path.extname(filename);
  34. var stats = FS.statSync(filepath);
  35. // don't require non-javascript files (.txt .md etc.)
  36. if (stats.isFile() && !(ext in require.extensions)) {
  37. return;
  38. }
  39. var basename = Path.basename(filename, ext);
  40. requires[basename] = require(filepath);
  41. });
  42. } else {
  43. throw new Error("Must pass directory as first argument");
  44. }
  45. return requires;
  46. };