UNPKG

908 BJavaScriptView Raw
1const fs = require('fs');
2const path = require('path');
3
4function findPackageJSON(curr) {
5 const parent = path.dirname(curr);
6 if (parent === curr || curr.length === 0) {
7 return null;
8 } else {
9 const pkg = path.join(curr, 'package.json');
10 if (fs.existsSync(pkg)) {
11 return {dir: curr, file: pkg};
12 } else {
13 return findPackageJSON(parent);
14 }
15 }
16}
17
18function findRoot(curr) {
19 const pkg = findPackageJSON(curr);
20 if (pkg) {
21 try {
22 const meta = require(pkg.file);
23 if (meta.name) {
24 return {path: pkg.dir, meta: meta};
25 } else {
26 return findRoot(path.resolve(pkg.dir, '..'));
27 }
28 } catch (e) {
29 return findRoot(path.resolve(pkg.dir, '..'));
30 }
31 } else {
32 throw new Error(
33 'Unable to locate project root directory. ' + 'Valid project-level package.json file not found.'
34 );
35 }
36}
37
38module.exports = function(start) {
39 return findRoot(path.resolve(start || process.cwd()));
40};