UNPKG

1.63 kBJavaScriptView Raw
1var FS = require('fs');
2var Path = require('path');
3
4module.exports = function (dir, basenames) {
5 var requires = {};
6
7 if (arguments.length === 2) {
8 // if basenames argument is passed, explicitly include those files
9 basenames.forEach(function (basename) {
10 var filepath = Path.resolve(Path.join(dir, basename));
11 requires[basename] = require(filepath);
12 });
13
14 } else if (arguments.length === 1) {
15 // if basenames arguments isn't passed, require all javascript
16 // files (except for those prefixed with _) and all directories
17
18 var files = FS.readdirSync(dir);
19
20 // sort files in lowercase alpha for linux
21 files.sort(function (a,b) {
22 a = a.toLowerCase();
23 b = b.toLowerCase();
24
25 if (a < b) {
26 return -1;
27 } else if (b < a) {
28 return 1;
29 } else {
30 return 0;
31 }
32 });
33
34 files.forEach(function (filename) {
35 // ignore index.js and files prefixed with underscore and
36 if ((filename === 'index.js') || (filename[0] === '_') || (filename[0] === '.')) {
37 return;
38 }
39
40 var filepath = Path.resolve(Path.join(dir, filename));
41 var ext = Path.extname(filename);
42 var stats = FS.statSync(filepath);
43
44 // don't require non-javascript files (.txt .md etc.)
45 var exts = ['.js', '.node', '.json'];
46 if (stats.isFile() && (exts.indexOf(ext) === -1)) {
47 return;
48 }
49
50 var basename = Path.basename(filename, ext);
51
52 requires[basename] = require(filepath);
53 });
54
55 } else {
56 throw new Error("Must pass directory as first argument");
57 }
58
59 return requires;
60};