This repository has been archived by the owner on Jan 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
context.js
47 lines (39 loc) · 1.29 KB
/
context.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
45
46
47
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;
let filepath = path.join(basedir, relativePath);
let stats = fs.lstatSync(filepath);
while (stats.isSymbolicLink()) {
filepath = fs.realpathSync(filepath);
stats = fs.lstatSync(filepath);
}
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 resolve(key) {
if (!keys.includes(key)) {
throw new Error(`Cannot find module '${key}'.`);
}
return require('path').resolve(absoluteDirectory, key);
}
function requireContext(key) {
return require(resolve(key));
}
requireContext.keys = () => keys;
requireContext.resolve = resolve;
return requireContext;
}
module.exports = context;