UNPKG

1.24 kBJavaScriptView Raw
1'use strict';
2
3var Module = require('module');
4var path = require('path');
5var 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 */
11function findModulePath(moduleName, currentState) {
12 var 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 var nodeModulesPaths = Module._nodeModulePaths(cwd);
23 var possibleModulePaths = nodeModulesPaths.map(function (x) {
24 return path.join(x, moduleName);
25 });
26 var modulePath = possibleModulePaths.find(pathExists.sync);
27
28 // if no existing path was found, return the first tried path anyway
29 return modulePath || path.join(cwd, moduleName);
30}
31
32module.exports = findModulePath;
\No newline at end of file