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