Created
May 22, 2015 22:48
-
-
Save elycruz/6866de600bf5a1705986 to your computer and use it in GitHub Desktop.
Php Styled Autoloader for NodeJs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by Ely on 5/22/2015. | |
*/ | |
require('sjljs'); | |
var path = require('path'), | |
fs = require('fs'); | |
var Namespace = sjl.Extendable.extend(function Namespace (dir, allowedFileExts) { | |
var self = this, | |
files = fs.readdirSync(dir); | |
allowedFileExts = allowedFileExts || ['.js', '.json']; | |
if (!sjl.empty(files)) { | |
_processFiles(files, dir, allowedFileExts, self); | |
} | |
}); | |
function _processFiles (files, dir, allowedFileExts, self) { | |
files.forEach(function (file) { | |
if (fs.statSync(path.join(dir, file)).isDirectory()) { | |
self[file] = new Namespace(path.join(dir, file)); | |
} | |
else if (allowedFileExts.indexOf(path.extname(file)) > -1) { | |
Object.defineProperty(self, file.substr(0, file.lastIndexOf('.')), { | |
get: function () { | |
return require(path.join(dir, file)) } | |
}); | |
} | |
else { | |
throw new Error('The file representing the requested alias is not of ' + | |
'the allowed type ...'); //@todo fill this out | |
} | |
}); | |
} | |
module.exports = Namespace; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment