Node.js Modules System

Posted by: Ravi Kiran , on 6/28/2015, in Category Node.js
Views: 15822
Abstract: Node.js modules system is based on the CommonJS modules system standard. We will explore three different types of modules in a typical Node.js application

Node.js is a platform for building server based applications using JavaScript. It is a light weight platform that can handle very high number of concurrent requests. It is also easy to get started and start serving pages and data on the platform. In addition to this, Node.js also comes with a CommonJS based module system to ease the work of loading dependent modules. The module system also helps in organizing the code written in Node.js and maintain separation of concerns (SoC) in the application.

Editorial Note: If you are new to Node.js, please go through these articles to get a good understanding of Node.

Node.js Tutorial Series - Getting Started

Node.js Serving HTML pages and Static content

Using Node.js to build REST APIs

CommonJS Modules System

As Node.js is based on JavaScript, it suffers from the same set of limitations that JavaScript has today. One of them is the lack of a built-in module system. CommonJS module system is an open standard for building modules in applications based on JavaScript. Node.js comes with a module system based on this standard.

Note: Though things are changing with ECMAScript 6 (a.k.a ECMAScript 2015), it will take some time for the specifications to be implemented by the browsers and other platforms.

The specification of CommonJS module system defines the following keywords:

  • require: It is a function available to all modules and is used to load other modules. It loads the module synchronously and returns an object containing the values exported from the imported object
  • exports: Every module gets this object. Values assigned to the exports object in a module are returned in the form of an object when the module is loaded using the require() function in another module

Getting Hands dirty with Modules in Node.js

Now that you have a fair idea of the CommonJS module system, let’s see how Node.js uses it. In a typical Node.js application, we need to deal with three different types of modules:

  • Global modules installed with Node.js installer
  • Local modules installed using the “npm install” command
  • Modules defined in the application

We need to know how to work with each of these types of modules to feel confident in dealing with the modules in Node.js.

Global modules

All global modules are directly accessible through the require() function. We don’t need to apply any additional setup to start using them. Node.js installs a number of essential modules and makes them available globally. Following are someexamples of them:

var fs = require('fs');
var http = require('http');
var connect = require('connect');

Modules installed in node_modules folder

The packages installed into an application using the “npm install” command are saved in the node_modules folder of the project and each package exposes a module. Name of the module exposed by the package is same as the package name. For example, if an application has the package express installed, module of the package can be loaded using the following statement:

var express = require('express');

Getting local modules

Every file in a Node.js application is treated as a module. One file can load another file as a module and use the objects exposed from it. For example, say the application has a file rivers.js in the root folder and another file at the same level wants to use it. The other module can refer this module using the following statement:

var rivers = require('./rivers');

A file defined in a folder in the same application can also be referred using similar syntax, we need to mention the folder name in the string passed to the require function. Following is an example of it:

var cities = require('./Features/cities');

Note: Though in most of the examples we find the require statements at the beginning of the module, it is not necessary to import all necessary modules at the beginning. We can load modules in any block of code.

Exporting Objects

Every module is an abstraction. A module can decide on making a set of its objects public or, private. The objects that have to be made accessible to other modules have to be assigned to the exports object. Any number of objects can be exported from a module. Following module exports the functions defined in the module:

var cities = [
    {name: 'Delhi', country: 'India'},
    {name: 'New York', country: 'USA'},
    {name: 'London', country:'England'}];

function add(city){
    for(var index = 0; index < cities.length; index++){
        if(cities[index].name ==={
            return -1;

    return 0;

function getAll(){
    return cities;

function getOne(cityName){
    for(var index = 0; index < cities.length; index++){
        if(cities[index].name === cityName){
            return cities[index];

    return {};

function modify(city){
    for(var index = 0; index < cities.length; index++){
        if(cities[index].name ==={
            cities[index].country =;
            return 0;

    return -1;

module.exports = {
    getAll: getAll,
    getOne: getOne,
    add: add,
    modify: modify

The collection cities is not exposed from the module, so it will remain private to the module. The members mentioned in the export object are made accessible through the return object of the require() function. Following is an example of an API using the getAll() method from the above module:

var cities = require('./Feature/cities'); 

var app = require('express')();

app.use(bodyParser.urlencoded({extended: true}));

app.get('/api/cities', function(request, response){


Being programmers, we always keep finding ways to modularize the code once it goes beyond certain limit. The module system in Node.js answers this problem pretty well. Let’s use it and write good code on the platform!

Download the entire source code of this article (Github)

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Rabi Kiran (a.k.a. Ravi Kiran) is a developer working on Microsoft Technologies at Hyderabad. These days, he is spending his time on JavaScript frameworks like AngularJS, latest updates to JavaScript in ES6 and ES7, Web Components, Node.js and also on several Microsoft technologies including ASP.NET 5, SignalR and C#. He is an active blogger, an author at SitePoint and at DotNetCurry. He is rewarded with Microsoft MVP (Visual Studio and Dev Tools) and DZone MVB awards for his contribution to the community

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!





C# Book for Building Concepts and Interviews



jQuery CookBook