NodeJS - Modules


In my previous article I gave an Introduction about NodeJS. In this article I will explain modules in NodeJS, loading modules, creating modules and about node_modules folder.
Node.js has a simple module loading system. A module in node.js is a simple or complex functionality organized in single or multiple javascript files which can be reusable again. 
Node.js Module Types 

In Node.js modules can be categorized in 3 types,
  1. Core Modules
  2. Local Modules
  3. Third Party Modules
Node.js Core Modules

Node.js has several modules compiled into its binary distribution, and load automatically when the Node.js process starts, these are called the core modules. These core modules of node.js  are located within Node.js's source and are locate d inside "lib" folder. Some of the core modules are listed below.
  • http - This module is used to create http server.
  • fs - This module is used to perform file operations like reading, writing, appending and deleting files etc. 
  • Crypto - This module provides cryptographic functionalities like encryption, decryption, sign, verification, digesting etc. 
  • Querystring - This method includes methods to deal with querystring like unescapeBuffer, unescape, escape,  encode, stringify, decode and parse. 
  • url - This module includes methods for url resolutions,resolve, parsing, format etc.
  • path - This module is used to deal with file paths when working with file system. 
Local Modules

Local modules are user defined modules which are mainly used for specific projects and locally available in separate files or folders within project folders. These type of modules contain application specific functionality.


We can package locally created local modules and distribute them via NPM (Node Package Manager), which can be used by others and the node community. 
Third party module

The third party module can be downloaded by NPM (Node Package Manager). These type of modules are developed by others and we can use that in our project. Some of the best third party module examples are listed as follows: express, gulp, lodash, async,, mongoose, underscore, pm2, bower, q, debug, react, mocha etc.

Third party modules can be install inside the project folder or globally.
How to load a module?

To load a module in your node application you can just use "require()" function. whose syntax is given below.
  1. var module=require('module_name');  
There are several ways to reference modules, this depends on what type of module we are going to load. 
Loading  core module

Core modules can be loaded as follows.
  1. var http=require('http');  
As I have already told you that code modules are loaded in "lib" directory, so in the above example http module will be loaded from lib folder.
How to create and load local module?

In Node.js files and modules are in a one-to-one correspondence. The following example will explain to you how to create a local Node.js module.
  1. function Circle(radius) {  
  2.  return {  
  3.     area: function area() {  
  4.     return Math.PI * Math.PI * radius;  
  5.     }  
  6.  };  
  7. }  
  8. module.exports = Circle;  
In the above example I have created a function which is used to find an area of the Circle. In this example in  the last line I have written "module.exports=Circle" this is a very important line here. Here module is a variable that represents the modules in which we are currently in. We can export any type of object.
I have saved the above file using "Circle.js". Now I am going to use this module inside another file, app.js, and the code is written as follows.
  1. var circle=require('./Circle.js');  
  2. var obj=circle(7);  
  3. var output=obj.area();  
  4. console.log(output);  
In the above example I am loading a file whose name is Circle.js using the require function which exports Circle object. 


Different ways for loading local node.js module

There are lots of ways to load locally created modules.
  • Using absolute path
    1. var module = require('/<folder_name1>/<folder_name2>/.../module');   
  • Using relative path
    1. var module = require('./module');   
    Here I am not giving .js extension so there is no need to add ".js"  Node finds .js files if we do not give .js as an extension, it means the following lines will be the same.
    1. var module = require('./module');   
    2. var module = require('./module.js');   
  • Using folder path

    You can also use folder path to load modules as follows:
    1. var module = require('./folder_name');   
    But a folder can contain lots of modules and javascript files so node finds index.js file and loads by default. Otherwise we can create package.json where we can define node module name which we want to load by default. We can write package.json like as follows.
    1. {  
    2.  "name" : "module_name",  
    3.  "main" : "./folder_path/module_name.js"  
    4. }   
Loading third party modules

Third party Node.js module can be downloaded using NPM (node package manager) which you can download locally or globally. To download globally we use the following command.
  1. npm install -g <module_name>  
here  we use -g to install package globally. If you want to install locally then use the following command.
  1. npm install --save <module_name>  
Above command will download node package inside node_modules folder and then you can directly use require function to load node module. 
  1. var module= require('module_name');   
Caching Modules

In Node.js modules are cached when module is loaded the first time. It means if you load the same node module 2 times then node.js does not load that module again it will copy that module from cache. Example is shown below. 
  1. console.log("Module Loaded Successfully");  
I have created a module that is My_Module and written the above code and saved it using My_Modules.js. Now I am creating app.js file where I am writing the following script.
  1. var my_module1=require('./My_Module');  
Above code will print the following.

Now I am modifying app.js and writing the following code.
  1. var my_module1=require('./My_Module');  
  2. var my_module2=require('./My_Module');  
In the above code I have created two objects for My_Module. But when you run it then you will get the following output.

This means that module initializes only once. This is very important to know if you are creating any module.

Similar Articles