index.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. var
  2. fs = require('fs'),
  3. path = require('path')
  4. ;
  5. // walks parent folders until a dot file is found
  6. module.exports = function(file, directory, maxSteps) {
  7. var
  8. steps = 0,
  9. requirePath,
  10. walk
  11. ;
  12. // recursion safety-net
  13. maxSteps = maxSteps || 20;
  14. walk = function(directory) {
  15. var
  16. nextDirectory = path.resolve( path.join(directory, path.sep, '..') ),
  17. currentPath = path.normalize( path.join(directory, file) )
  18. ;
  19. if( fs.existsSync(currentPath) ) {
  20. // found file
  21. requirePath = path.normalize(currentPath);
  22. return;
  23. }
  24. else {
  25. // reached file system root, let's stop
  26. if(nextDirectory == directory || steps >= maxSteps ) {
  27. return;
  28. }
  29. // otherwise recurse
  30. steps++;
  31. walk(nextDirectory, file);
  32. }
  33. };
  34. // start walk from outside require-dot-files directory
  35. directory = directory || path.join(__dirname, path.sep , '..');
  36. walk(directory);
  37. if(!requirePath) {
  38. // throw new Error('Unable to find: ' + file);
  39. return false;
  40. }
  41. return require(requirePath);
  42. };