Skip to content

Instantly share code, notes, and snippets.

@gansbrest
Created January 22, 2013 18:35
Show Gist options
  • Save gansbrest/4597035 to your computer and use it in GitHub Desktop.
Save gansbrest/4597035 to your computer and use it in GitHub Desktop.
Nodejs submodules lazyloading, could be very useful for private modules repos
// Nodejs submodules lazyloading, very useful for private modules repos
// where you don't want to create separate repo for evey module
// using this snippet, you can create one main repo for private modules
// and create submodules inside subfolder with the same name.
var fs = require('fs');
exports.answer = 42; // Some existing property
// This is how you would do it without lazy loading
// basically u would need to require every submodule right away
// even if you don't need it right away
//
// exports.sub1 = require('./submodules/sub1');
// This is where lazyloading magic for nodejs happens
fs.readdirSync(__dirname + '/submodules').forEach(function (plugin) {
plugin = plugin.replace('.js', '');
// __defineGetter__ is a getter method which will be called if particluar
// property (or submodule in our case) will be requested
exports.__defineGetter__(plugin, function () {
return require('./submodules/' + plugin);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment