Zachary Berry

Designer & Developer

Creating a custom node.js module with the Revealing Module pattern

Creating a custom node.js module with the Revealing Module pattern

So you want to utilize the revealing module pattern in a custom node.js module? It’s not hard but it wasn’t immediately obvious to me, so here’s how you do it.

Every node.js module is just a simple javascript file that contains a special exports variable. That exports variable is what gets exposed to the class that requires your module.

For example, take a custom module mymodule.js:

exports.animal = 'kitties';

Here’s how you’d use it:

var myModule = require('./mymodule.js');

console.log(myModule.animal); // prints 'kitties'

I got this far thanks to How to Node’s article Creating Custom Modules.

Creating your module with the revealing module pattern is not that much of a step. Here’s our new fancymodule.js:

module.exports = function()
{
var animal = 'kitties';

    function getAnimal()
    {
    	return animal;
    }

    return {
    	getAnimal: getAnimal
    };

}();

The key is setting the whole module to module.exports rather than simply using module.

And how to use it:

var myFancyModule = require('./fancymodule.js');

console.log(myFancyModule.getAnimal()) // prints 'kitties'

Not that complicated, but I just got it working so I wanted to spread the word.

comments powered by Disqus