Node.js is all about modules. For every program we use already built modules. Like http module, fs module, nodemailer module, formidable module, express module.

  • Modules are javascript libraries
  • Modules are used for different purposes.
  • In order to use any module it needs to be installed on the system.
  • Modules are installed using
  • npm install modulename


Features of Modules in Node.js

  • It contains set of functions that you need to implement in your program.
  • Types of Module
  • http module – Create client server application
  • Fs module – it is used for all the files related operations (read a file, write a file)
  • url module – it is used to parse url
  • Nodemailer module – to send email
  • Formidable module – to upload files on the server

How to use Modules in Node.js Program

In node.js we use require function to include the module in the code. Below is the sample code to use module.

First we include the module in the program

varhttp = require(‘http’);

http.createServer(function (req, res) {
res.writeHead(200, {‘Content-Type’: ‘text/html’});
res.end(‘Hello World!’);

How to create custom module in node.js

  • You can create your own module using exports keywords.
  • Using export keyword module is available outside the file.
  • Create a new file “custom.js”
  • exports.newfunc= function () {
    return Date();

Save the file “custom.js”

Now you can use the above custom module in your new program :

var http = require(‘http’);
var dt = require(‘./custom’);

http.createServer(function (req, res) {
res.writeHead(200, {‘Content-Type’: ‘text/html’});
res.write(“The date and time are currently: ” + dt.newfunc());



984total visits,1visits today