1 | ;
|
2 |
|
3 | const Module = require('module');
|
4 | const path = require('path');
|
5 | const pathExists = require('path-exists');
|
6 |
|
7 | /**
|
8 | * Searches the directory hierarchy to return the path to the requested node module.
|
9 | * If the module can't be found, returns the initial (deepest) tried path.
|
10 | */
|
11 | function findModulePath(moduleName, currentState) {
|
12 | const cwd = currentState.get('cwd');
|
13 |
|
14 | if (currentState.get('global')) {
|
15 | return path.join(cwd, moduleName);
|
16 | }
|
17 |
|
18 | // Module._nodeModulePaths does not include some places the node module resolver searches, such as
|
19 | // the global prefix or other special directories. This is desirable because if a module is missing
|
20 | // in the project directory we want to be sure to report it as missing.
|
21 | // We can't use require.resolve because it fails if the module doesn't have an entry point.
|
22 | const nodeModulesPaths = Module._nodeModulePaths(cwd);
|
23 | const possibleModulePaths = nodeModulesPaths.map(x => path.join(x, moduleName));
|
24 | const modulePath = possibleModulePaths.find(pathExists.sync);
|
25 |
|
26 | // if no existing path was found, return the first tried path anyway
|
27 | return modulePath || path.join(cwd, moduleName);
|
28 | }
|
29 |
|
30 | module.exports = findModulePath;
|