JavaScript Modularization Techniques CommonJS - Node.js


CommonJS is a popular modularization pattern that's used in Node.js.

The CommonJS system is centered around a require() function that loads other modules and an exports property that lets modules export publicly accessible methods.

Here's an example of CommonJS, we'll load Lodash and Node.js' fs module:

// Load fs and lodash, we can use them anywhere inside the module
var fs = require("fs"),
    _ = require("lodash");

var myPrivateFn = function(param) {
    return "Here's what you said: " + param;

// Here we export a public `myMethod` that other modules can use
exports.myMethod = function(param) {
    return myPrivateFn(param);

You can also export a function as the entire module using module.exports:

module.exports = function() {
    return "Hello!";