index.js 1008 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. };