-
Notifications
You must be signed in to change notification settings - Fork 2
/
include.js
52 lines (44 loc) · 1.23 KB
/
include.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
'use strict';
// Node
var lstatSync = require('fs').lstatSync;
var path = require('path');
/**
* Attempts to find the project root by finding the nearest package.json file.
* @private
* @param {String} currentPath - Path of the file doing the including.
* @return {String?}
*/
function findProjectRoot(currentPath) {
var result = undefined;
try {
var packageStats = lstatSync(path.join(currentPath, 'package.json'));
if (packageStats.isFile()) {
result = currentPath;
}
} catch (error) {
if (currentPath !== path.resolve('/')) {
result = findProjectRoot(path.join(currentPath, '..'));
}
}
return result;
}
/**
* Creates the include function wrapper around <code>require</code> based on the path of the calling file and not the
* install location of the module.
* @param {String} callerPath - Path of the calling file.
* @return {Function}
* @example
*
* var include = require('include')(__dirname);
*
* var projectFn = include('src/method');
*/
function createInclude(callerPath) {
return function (target) {
var projectRoot = findProjectRoot(callerPath);
return projectRoot ?
require(path.join(projectRoot, target)) :
require(target);
};
}
module.exports = createInclude;