UNPKG

1.94 kBJavaScriptView Raw
1'use strict';
2
3var fs = require('fs');
4var systemPath = require('path');
5
6
7// Patch system path to add a filename function.
8// filename("something.js") => "something"
9var filename = function(path) {
10 var extension = systemPath.extname(path);
11 return path.substr(0, path.length - extension.length);
12};
13
14
15// Convert hyphens to camel case
16// camelCase("hello-world") => "helloWorld"
17var camelCase = function(input) {
18 return input.replace(/-(.)/g, function(match, firstLetter) {
19 return firstLetter.toUpperCase();
20 });
21};
22
23
24// Walk all files and folders in path to build tree
25var walk = function(path, options) {
26 var tree = {};
27 fs.readdirSync(path).forEach(function(file) {
28 var name;
29 var newPath = path + '/' + file;
30 var stat = fs.statSync(newPath);
31 if (stat.isFile()) {
32 var extension = systemPath.extname(file);
33 if(extension === '.js' && options.js) {
34 name = filename(file);
35 name = camelCase(name);
36 tree[name] = require(newPath);
37 }
38 else if(extension === '.json' && options.json) {
39 name = filename(file);
40 name = camelCase(name);
41 tree[name] = require(newPath);
42 }
43 } else if (stat.isDirectory() && options.deep) {
44 name = camelCase(file);
45 tree[name] = walk(newPath, options);
46 }
47 });
48
49 return tree;
50};
51
52
53// Main function.
54module.exports = function autoload(baseDirectory, options) {
55
56 options = options || {};
57 if (options.deep === undefined) {
58 options.deep = true;
59 }
60 if (options.js === undefined) {
61 options.js = true;
62 }
63 if (options.json === undefined) {
64 options.json = true;
65 }
66
67 // Check if it's absolute
68 // http://stackoverflow.com/q/21698906/938236
69 var normalized = systemPath.normalize(baseDirectory).replace(/[\/|\\]$/, '');
70 if (systemPath.resolve(baseDirectory) !== normalized) {
71 baseDirectory = process.cwd() + '/' + baseDirectory;
72 }
73 return walk(baseDirectory, options);
74};