Skip to content

Instantly share code, notes, and snippets.

@jescalan
Last active December 22, 2016 14:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jescalan/11016226 to your computer and use it in GitHub Desktop.
Save jescalan/11016226 to your computer and use it in GitHub Desktop.
lazy-loading require in node
/**
* Requires a library, but only loads it when it's actually used.
*
* lazy_require('fs');
* fs.readFileSync('example.js');
*
* var wow = lazy_require('fs');
* wow.readFileSync('example.js');
*
* @param {String} lib - name of the lib you want to load
* @param {String} name - name of the var you want to assign the lib to, defaults to lib name
* @return {*} a getter for the library you wanted to load
*/
lazy_require = function(lib, name){
if (!name) name = lib;
this.__defineGetter__(name, function(){ return require(lib) });
return this[name]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment