index.js 1008 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. const path = require('path');
  3. const locatePath = require('locate-path');
  4. module.exports = (filename, opts) => {
  5. opts = opts || {};
  6. const startDir = path.resolve(opts.cwd || '');
  7. const root = path.parse(startDir).root;
  8. const filenames = [].concat(filename);
  9. return new Promise(resolve => {
  10. (function find(dir) {
  11. locatePath(filenames, {cwd: dir}).then(file => {
  12. if (file) {
  13. resolve(path.join(dir, file));
  14. } else if (dir === root) {
  15. resolve(null);
  16. } else {
  17. find(path.dirname(dir));
  18. }
  19. });
  20. })(startDir);
  21. });
  22. };
  23. module.exports.sync = (filename, opts) => {
  24. opts = opts || {};
  25. let dir = path.resolve(opts.cwd || '');
  26. const root = path.parse(dir).root;
  27. const filenames = [].concat(filename);
  28. // eslint-disable-next-line no-constant-condition
  29. while (true) {
  30. const file = locatePath.sync(filenames, {cwd: dir});
  31. if (file) {
  32. return path.join(dir, file);
  33. } else if (dir === root) {
  34. return null;
  35. }
  36. dir = path.dirname(dir);
  37. }
  38. };