Lazy loading of modules in nodejs

This is a pattern I found in pkgcloud to lazy-load nodejs modules. That is, to defer their loading until a module is actually needed.

  var providers = [ 'amazon', 'azure', ..., 'joyent' ];

  // Setup all providers as lazy-loaded getters
  providers.forEach(function (provider) {
    pkgcloud.providers.__defineGetter__(provider, function () {
      return require('./pkgcloud/' + provider);

It basically defines a getter, so modules won’t be loaded until you do:

var provider =;

It might be useful in applications where you have different adapters (“providers” in the example above) offering different implementations of the same API, and you want to let the user choose which one to use at runtime. This is a common requirement in cloud environments but it could be applicable to other scenarios as well (e.g. choose a payment gateway).

This is the first time I see it, so please share your thoughts on it and any other alternative approaches.