Node.js Module With Examples

This article will explain Node.js and its modules with examples, and we will create our own custom server using the Node.js application.
 
To understand and create the Node.js application, please download and install it from the official site: node.js 
 

Node.js

 
According to official documentation,
  • Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine for easily building fast and scalable network applications. 
  • Node.js is free
  • Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
  • Node.js uses JavaScript on the server
  • Node.js modules
Module in Node.js is a simple or complex functionality organized in single or multiple JavaScript files which can be reused throughout the Node. js application.
 
In short we can break large javascript files into multiple files and reuse it.
 
Let's create your first project in node.js application 
 
Hello World
 
Step 1
 
Open command prompt and navigate to your project directory (My project directory is D:\Arvind\solution\nodesolution\nodeExamples).
 
Step 2
 
Type npm init and answer the following question as per the following details.
 
Node.js Module With Examples
 
Step 3 
 
To create a blank .js file type the below command (It will create blank index.js in our current directory).
  1. type Nul > index.js  
Step 4
 
Open index.js file in your editor (visual studio code) and write the below code.
  1. console.log("Hello World")  
Step 5 
 
To run and see the ouput type node index.
  1. node index  
Node.js Module With Examples
 
Since we had completed our first project in node.js application, let's see the node modules.
 

Node.js Module Types

 
There are basically three types of modules,
  • File based Modules
  • Core Modules
  • External or Third Party Modules
File based Modules
 
This types of modules are created locally in your node.js application. It includes different functionalities of your application in seperate files and folders.
 
The require function is used to import a module in nodes.js application.
 
Example 
 
Create LocalModule.js file and insert the follwing code.
  1. // create a variable calc that have four function add, subtract, multiply and divide.  
  2.   
  3. const calc = {  
  4.     // Add the two number  
  5.     add: function (num1, num2) {  
  6.         return num1 + num2  
  7.     },  
  8.     // Subtract the two number  
  9.     subtract: function (num1, num2) {  
  10.         return num1 - num2;  
  11.     },  
  12.     // multiply the two number  
  13.     multiply: function (num1, num2) {  
  14.         return num1 * num2;  
  15.     },  
  16.     // divide the two number  
  17.     divide: function (num1, num2) {  
  18.         return num1 / num2  
  19.     }  
  20. };  
  21.   
  22. // export the modules to consume on different modules.  
  23. module.exports.calc = calc;  
 To use the above functionality in a different module, create index.js and write the code
  1. // To use custom module declare the code like this.  
  2. const myCalculation = require('./LocalModule.js');  
  3. // Declare two variable  
  4. const num1 = 5;  
  5. const num2 = 4;  
  6.   
  7. // consume the existing function from LocalModule.js  
  8.    
  9. console.log(`Addition of ${num1} and ${num2} is:  ${myCalculation.calc.add(num1, num2)}`);  
  10. console.log(`Subtraction of ${num1} and ${num2} is: ` + myCalculation.calc.subtract(num1, num2));  
  11. console.log(`Multiply of ${num1} and ${num2} is: ` + myCalculation.calc.multiply(num1, num2));  
  12. console.log(`Divide of ${num1} and ${num2} is: ` + myCalculation.calc.divide(num1, num2));  
Now type node LocalModule to see the ouput.
 
Node.js Module With Examples
 
Core Modules
 
It is also known as (built in modules).
 
These core modules are compiled into its binary distribution and load automatically when Node.js process starts.
 
In order to use Node.js core or NPM modules, you first need to import it using require() function as shown below.
  1. const variableName = require('module_name');  
  2. const path = require('path');  
Example
 
Write the below code in CoreModule.js file.
  1. // declare the core library file.  
  2. const path = require('path');  
  3.   
  4. //Use the core library file.  
  5. console.log("Directory of index file: " + path.dirname(__filename));  
  6. console.log("Extension of index file: " + path.extname(__filename));  
  7.   
  8. // check more detail on path library from here https://nodejs.org/dist/latest-v12.x/docs/api/path.html  
  9. // For rest of core libary https://nodejs.org/dist/latest-v12.x/docs/api/ 
To see the ouput type command node CoreModule
 
Node.js Module With Examples
 
External or Third Party Module 
 
As the name suggests it is a third party module which needs to install in order to use in your node.js application by using NPM (Node Package Manager).
 
It will create node_modules folder in your node application.
 
Example 
 
To demonstrate third party or external modules, I have used the third party module https://www.npmjs.com/package/dota2-heroes which contains function random() and it gives the random hero's name wherever we call random function.
 
To use the above library first we have to install it and then use it by importing require('dota2-heroes') in your node application.
 
To install the library write the below command in your terminal. 
  1. npm i dota2-heroes  
To consume the above library in your application, write below code in ThirdPartyModule.js file 
  1. //https://www.npmjs.com/package/dota2-heroes  
  2. // First install by using command npm i dota2-heroes  
  3.   
  4. // To consume the above module  
  5. const names = require('dota2-heroes');  
  6.   
  7. // call the existing method  
  8. const randomName = names.random();  
  9.   
  10. // print the heroes  
  11. console.log("Heroes Name is :" + randomName);  
To see the ouput type command node ThirdPartyModule
 
Node.js Module With Examples
 

Create Custom Server using node.js 

 
Let's create the custom server step by step. 
 
Step 1
 
Open command prompt and create package.json file by using command
  1. npm init   
Step 2
 
Create blank index.js file by using command 
  1. type Nul > index.js    
 Step 3
 
 Create file customserver.js and write the below code.
  1. // import core library files  
  2. const httpOperation = require('http');  
  3. const fileOps = require('fs');  
  4. const path = require('path');  
  5.   
  6. // declare two variables  
  7. const hostName = "localhost";  
  8. const port = 9999;  
  9.   
  10. /** 
  11.  * This method is used to create server by using http methods 
  12.  *  
  13.  * @param {*} request It will contains request data like. GET Method or POST method, URL. 
  14.  *  
  15.  * @param {*} response It will provide the response depends upon the request. 
  16.  *  
  17.  */  
  18. const server = httpOperation.createServer((request, response) => {  
  19.     // check method is 'GET method or not'  
  20.     if (request.method === 'GET') {  
  21.         let fileUrl;  
  22.         // check the request url. If it constains only ('/') then navigate to index.html  
  23.         if (request.url === '/') {  
  24.             fileUrl = "/index.html";  
  25.         } else { // if not then pass the requested url.  
  26.             fileUrl = request.url;  
  27.         }  
  28.         // Now resolve the path by providing the complete file location  
  29.         let filePath = path.resolve('./HTML' + fileUrl);  
  30.         // Get the file extension   
  31.         const fileExt = path.extname(filePath);  
  32.         // check file is html file or not  
  33.         if (fileExt === '.html') {  
  34.             fileOps.exists(filePath, (isExists) => { // write the call back function if file exists or not  
  35.                 if (isExists) { // If requested file exist in filepath then show the index.html  
  36.                     response.statusCode = 200;  
  37.                     response.setHeader('Content-Type''text/html');  
  38.                     fileOps.createReadStream(filePath).pipe(response);  
  39.                 } else { // else show the file doesnot exist with 404 error.  
  40.                     showError(response, fileUrl, 'is not exist.');  
  41.                 }  
  42.   
  43.             });  
  44.         } else {  
  45.             // else show the file is not a HTML file with 404 error.  
  46.             showError(response, fileUrl, 'is not HTML file.');  
  47.         }  
  48.   
  49.     } else {  
  50.         // else show the request method is not GET with 404 error.  
  51.         showError(response, fileUrl, 'is not GET Method.')  
  52.     }  
  53.   
  54. });  
  55.   
  56. /** 
  57.  * This function is used to show error messages. 
  58.  *  
  59.  * @param {*} response Pass the response variable 
  60.  * @param {*} fileUrl pass the file url 
  61.  * @param {*} errorMsg pass the errorMsg 
  62.  */  
  63. function showError(response, fileUrl, errorMsg) {  
  64.     response.statusCode = 404;  
  65.     response.setHeader('Content-Type''text/html');  
  66.     response.end('<html><body><h1>Error 404 ' + fileUrl + ' ' + errorMsg + '</h1></body></html>');  
  67. }  
  68. server.listen(port, hostName, () => {  
  69.     console.log(`Server run at http://${hostName}:${port}`);  
  70. });  
 Step 4
 
 Create index.html file under HTML folder and write below code.
 
 Note
I have created simple index.html file for demonstration purpose.
  1. <html>  
  2.     <body>  
  3.         <h1>  
  4.             Welcome to node.js tutorial   
  5.         </h1>  
  6.     </body>  
  7. </html>  
Step 5
 
Write one line code in package.json file under script tag "start": "node customserver"
 
Node.js Module With Examples 
 
Step 6 
 
To start the server type the below command:
  1. npm start  
Step 7
 
To see the ouput browse http://localhost:9999 which shows 'welcome to node.js tutorial' on the page.
 
 You can download all the source code from the attachment.