-
Notifications
You must be signed in to change notification settings - Fork 14
/
register.js
44 lines (38 loc) · 1.07 KB
/
register.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
function context(
basedir,
directory,
useSubdirectories = false,
regExp = /^\.\//
) {
const path = require('path');
const fs = require('fs');
function enumerateFiles(basedir, dir) {
let result = [];
fs.readdirSync(path.join(basedir, dir)).forEach(function(file) {
const relativePath = dir + '/' + file;
const stats = fs.lstatSync(path.join(basedir, relativePath));
if (stats.isDirectory()) {
if (useSubdirectories) {
result = result.concat(enumerateFiles(basedir, relativePath));
}
} else if (regExp.test(relativePath)) {
result.push(relativePath);
}
});
return result;
}
const absoluteDirectory = path.resolve(basedir, directory);
const keys = enumerateFiles(absoluteDirectory, '.');
function requireContext(key) {
if (!keys.includes(key)) {
throw new Error(`Cannot find module '${key}'.`);
}
const fullKey = require('path').resolve(absoluteDirectory, key);
return require(fullKey);
}
requireContext.keys = () => keys;
return requireContext;
}
module.exports = function register() {
global.__requireContext = context;
};