UNPKG

2.34 kBJavaScriptView Raw
1'use strict';
2
3// Dependencies
4var path = require('path');
5
6// Load global paths
7var globalPaths = require('module').globalPaths;
8
9// Guess at NPM's global install dir
10var npmGlobalPrefix;
11if ('win32' === process.platform) {
12 npmGlobalPrefix = path.dirname(process.execPath);
13} else {
14 npmGlobalPrefix = path.dirname(path.dirname(process.execPath));
15}
16var npmGlobalModuleDir = path.resolve(npmGlobalPrefix, 'lib', 'node_modules');
17
18// Save OS-specific path separator
19var sep = path.sep;
20
21// Resolver
22module.exports = function resolve(dirname) {
23 // Check for environmental variable
24 if (process.env.APP_ROOT_PATH) {
25 return path.resolve(process.env.APP_ROOT_PATH);
26 }
27
28 // Defer to main process in electron renderer
29 if ('undefined' !== typeof window && window.process && 'renderer' === window.process.type) {
30 var electron = 'electron';
31 var remote = require(electron).remote;
32 return remote.require('app-root-path').path;
33 }
34
35 // Defer to AWS Lambda when executing there
36 if (process.env.LAMBDA_TASK_ROOT && process.env.AWS_EXECUTION_ENV) {
37 return process.env.LAMBDA_TASK_ROOT;
38 }
39
40 var resolved = path.resolve(dirname);
41 var alternateMethod = false;
42 var appRootPath = null;
43
44 // Make sure that we're not loaded from a global include path
45 // Eg. $HOME/.node_modules
46 // $HOME/.node_libraries
47 // $PREFIX/lib/node
48 globalPaths.forEach(function(globalPath) {
49 if (!alternateMethod && 0 === resolved.indexOf(globalPath)) {
50 alternateMethod = true;
51 }
52 });
53
54 // If the app-root-path library isn't loaded globally,
55 // and node_modules exists in the path, just split __dirname
56 var nodeModulesDir = sep + 'node_modules';
57 if (!alternateMethod && -1 !== resolved.indexOf(nodeModulesDir)) {
58 var parts = resolved.split(nodeModulesDir);
59 if (parts.length) {
60 appRootPath = parts[0];
61 parts = null;
62 }
63 }
64
65 // If the above didn't work, or this module is loaded globally, then
66 // resort to require.main.filename (See http://nodejs.org/api/modules.html)
67 if (alternateMethod || null == appRootPath) {
68 appRootPath = path.dirname(require.main.filename);
69 }
70
71 // Handle global bin/ directory edge-case
72 if (alternateMethod && -1 !== appRootPath.indexOf(npmGlobalModuleDir) && (appRootPath.length - 4) === appRootPath.indexOf(sep + 'bin')) {
73 appRootPath = appRootPath.slice(0, -4);
74 }
75
76 // Return
77 return appRootPath;
78};