Nodejs Module

Nodejs Module is like a set of libraries. There are two types of Module
1) Package Module
2) Custom Module

1) Package Module:- This type of module is already created by the NPM community and you can use this.

Step1:- Firstly installed the package
Example:- You want to install http module then write below command


npm install http --save

Step2:- Now, create the index.js file and include the module through require method.


var http = require('http');
const httpServer = http.createServer(app);
httpServer.listen(4444,() => {
 console.log('HTTP Server running on port 4444');
});

2) Custom Module:- You can create your own module.

Suppose, you create a register.js file and write the signup method


module.exports.signup= async ()=>{

// logic implement in this
console.log("signup module is called");

}

Now, create the index.js file and include the register.js file through require method and call the signup method.


var register = require('register');
var data=register.signup();
console.log(data);
Output:-
signup module is called

How to call one file method into another file?

If you want to call one file method into another file then you must define the method through module.exports

Example:- Suppose, You create a file user_info.js and define the method user_details()


module.exports.user_details = async () => {

  var udetails={

    name:"John",
    age:35

  }
  console.log(udetails);
}

Now, create the index.js file and call the user_details method.


var user_info= require('./user_info');
user_info.user_details()
Output:-
{ name: ‘John’, age: 35 }

If you do not define the module.exports

You create a file user_info.js and define the method user_details()


user_details = async () => {

  var udetails={

    name:"John",
    age:35

  }
  console.log(udetails);
}

Now, create the index.js file and call the user_details method.


var user_info= require('./user_info');
user_info.user_details()
Output:-
TypeError: user_info.user_details is not a function