Lazy loading of modules in nodejs

by Guido García on 27/03/2014

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 = pkgcloud.providers.amazon;

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.

 
77 Likes
Hold on

There are 2 comments in this article:

  1. 15/08/2014lijinma says:

    Thank you for share.

    Module lazy loading has a small problem: require() is synchronous and loads the module from disk.

    So best practice is to load any modules you need at application start before your application starts serving requests which then ensures that only asynchronous IO happens while your application is operational.

  2. 25/08/2014Guido García says:

    Thanks lijinma. That is right, but in many cases (e.g. in the example above) you only call require once. In those cases a single sync call to “require” might be worth it.

Write a comment: