Many times we uses modules in nodejs applications which comes from different package added in package.json file. This allows us to organize the code and to create reusable components.
Here are simple steps to create your own custom module.
Create a module file mymodule.js
exports.myServerTime = function () {
return "Today is "+Date();
};
In the above code, you would notice a keyword "exports" which make properties and menthods of this module outside of this module file.
Using the above module
To use this module, you need to use require function.
const http=require('http');
var mymodule=require('./mymodule');
const server=http.createServer((req,res)=>{
res.writeHead(200,{'Content-Type':'text/plan'})
res.write(mymodule.myServerTime());
res.end();
});
server.listen(8000)