-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpackage-root.js
More file actions
40 lines (37 loc) · 909 Bytes
/
package-root.js
File metadata and controls
40 lines (37 loc) · 909 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const fs = require('fs');
const path = require('path');
function findPackageJSON(curr) {
const parent = path.dirname(curr);
if (parent === curr || curr.length === 0) {
return null;
} else {
const pkg = path.join(curr, 'package.json');
if (fs.existsSync(pkg)) {
return {dir: curr, file: pkg};
} else {
return findPackageJSON(parent);
}
}
}
function findRoot(curr) {
const pkg = findPackageJSON(curr);
if (pkg) {
try {
const meta = require(pkg.file);
if (meta.name) {
return {path: pkg.dir, meta: meta};
} else {
return findRoot(path.resolve(pkg.dir, '..'));
}
} catch (e) {
return findRoot(path.resolve(pkg.dir, '..'));
}
} else {
throw new Error(
'Unable to locate project root directory. ' + 'Valid project-level package.json file not found.'
);
}
}
module.exports = function (start) {
return findRoot(path.resolve(start || process.cwd()));
};