Skip to content

Instantly share code, notes, and snippets.

@elycruz
Created May 22, 2015 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elycruz/6866de600bf5a1705986 to your computer and use it in GitHub Desktop.
Save elycruz/6866de600bf5a1705986 to your computer and use it in GitHub Desktop.
Php Styled Autoloader for NodeJs
/**
* 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