-
Notifications
You must be signed in to change notification settings - Fork 9
/
requireUp.js
38 lines (35 loc) · 1.13 KB
/
requireUp.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
var path = require('path');
/**
* Attempt to require a file, recursively checking parent directories until found.
* Similar to native `require` behavior, but doesn't check in `node_modules` folders.
* Based on https://github.com/js-cli/node-findup-sync.
*
* @param filename {string} The name of the target file
* @param exts {string[]} The file extensions to look for (e.g. '.cjs')
* @param cwd {string} The directory to search in
*/
function requireUp(filename, exts, cwd) {
for (var i = 0; i < exts.length; i++) {
var filepath = path.resolve(cwd, filename) + exts[i];
try {
return require(filepath);
} catch (error) {
var filepathNotFound =
error.code === 'MODULE_NOT_FOUND' &&
error.message.includes(`Cannot find module '${filepath}'`);
// Rethrow unless error is just saying `filepath` not found (in that case,
// let next loop check parent directory instead).
if (!filepathNotFound) {
throw error;
}
}
}
var dir = path.dirname(cwd);
if (dir === cwd) {
return undefined;
}
return requireUp(filename, exts, dir);
}
module.exports = {
requireUp,
};