-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
79 lines (66 loc) · 2.16 KB
/
index.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/* eslint-disable global-require */
'use strict';
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
module.exports = {
jsfiles: _jsfiles,
};
/**
* @typedef {Object} options
* @property {Object} initObject If set, will execute required file with initObject as param
* @property {Boolean} [includeUnderscore=false] Include _underscore files/folders
* @property {Boolean} [ignoreDirectories=false] Ignore directories
* @example <caption>Example of options</caption>
* {
* initObject: {
* someKey: "SOME_VALUE",
* someOtherKey: "SOME_OTHER_VALUE",
* },
* includeUnderscore: true,
* ignoreDirectories: true,
* }
*/
function _jsfiles(indexFile, options) {
var autoLoad = {};
var moduleFiles = fs.readdirSync(
path.dirname(
fs.realpathSync(indexFile)
)
);
// eslint-disable-next-line
function notIndexOrUnderscoreAndJsOrDir(fileToLoad) {
if (
fs.statSync(path.join(path.dirname(indexFile), fileToLoad)).isDirectory()
&& !_.get(options, 'ignoreDirectories')
&& (_.get(options, 'includeUnderscore') || !fileToLoad.match(/^_.*/))
&& !fileToLoad.match(/^lib$/)
) {
return true;
}
if (
fileToLoad === 'index.js'
|| !_.get(options, 'includeUnderscore') && fileToLoad.match(/^_.*/)
|| !fileToLoad.match(/.*\.js(on)?$/)
) {
return false;
}
return true;
}
function requireMapFunction(fileToLoad) {
if (
!_.get(options, 'initObject')
|| fs.statSync(path.join(path.dirname(indexFile), fileToLoad)).isDirectory()
) {
return autoLoad[fileToLoad.replace(/\.js(on)?$/, '')]
= require(path.join(path.dirname(indexFile), fileToLoad));
}
return autoLoad[fileToLoad.replace(/\.js(on)?$/, '')]
= require(path.join(path.dirname(indexFile), fileToLoad))(options.initObject);
}
_.map(
_.filter(moduleFiles, notIndexOrUnderscoreAndJsOrDir),
requireMapFunction
);
return autoLoad;
}