-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
59 lines (46 loc) · 1.32 KB
/
index.js
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
var path = require('path');
var fs = require('fs');
// TODO: memoize with limit?
function findPackageDir(dir) {
var dirContainsPackage = fs.existsSync(path.join(dir, 'package.json'));
if (dirContainsPackage) {
return dir;
}
var parentDir = path.resolve(dir, '..');
// if root directory is reached without finding package file
if (parentDir === dir) {
throw new Error('package directory not found');
}
// recursively look for package in parent dir
return findPackageDir(parentDir);
}
function pkgRequireFactory(packageDir) {
function resolve(relativePath) {
return path.join(packageDir, relativePath);
}
function root() {
return packageDir;
}
function requireInPkg(relativePath) {
return require(resolve(relativePath));
}
requireInPkg.resolve = resolve;
requireInPkg.root = root;
return requireInPkg;
}
function createInstance(currentDirectory) {
if (
!currentDirectory
|| typeof currentDirectory !== 'string'
|| !path.isAbsolute(currentDirectory)
) {
throw new Error('module must be called with an absolute path as argument, '
+ "eg: require('pkg-require')(__dirname), "
+ 'instead received: '
+ currentDirectory
);
}
var packageDir = findPackageDir(currentDirectory);
return pkgRequireFactory(packageDir);
}
module.exports = createInstance;