NodeJs – Modules

NodeJs Modules :

It is a simple or complex functionality which is organized as javascript files. it can reusable throughout the NodeJs application.Modules are same as Javascript Libraries or a set of functon include in your application.

How to include Modules :
If you want include your module ,use the require() function with name of the module.
For example :

var http = require('http');
//where http inside the require is an module that 
    //allows you to access the http module to create server. 

Built-In Modules :
In NodeJs we have set of built-in functions we can use it without any further installation.
Example:

“events” To handle events
“fs” To handle the file system
“http” To make Node.js act as an HTTP server
“https” To make Node.js act as an HTTPS server
“net” To create servers and clients
“os” Provides information about the operation system
“path” To handle file paths

Create your own module :
If you want to create your own module that can be reusable over NodeJs application.
Example :

exports.myDateTime = function () {
   return Date();
   //The javascript Date() of is an in-built function 
      //can return a current date and time.
 };

export is a keyword that allows outside the module access to a properties and methods.
save the above code in a file name called dateTimemodule.js

You may ask how we can access this module over NodeJs application.
let see the below example :

var http = require('http');
var uDate = require('./dateTimemodule');
//Import a module to fetch the current Date and Time
http.createServer(function (req, res) {
   res.writeHead(200, {'Content-Type': 'text/html'});
   res.write("The date and time are currently: " + uDate.myDateTime());
   res.end();
 }).listen(5050);

To locate the module we have to use this ./ that means the file is located inside the folder only .
Save the above code “userModule.js”

Run the file in your Cmd prompt:
D:\node project >node userModule.js

Result:

Start your internet browser, and type in the address: http://localhost:5050

Next Chapter -> File System

Leave a Reply

Your email address will not be published. Required fields are marked *