How to create Node.js Module
Node.js has a set of modules that are built in.Example of these built-in modules are.
1.http-creates http server.
2.fs-to handle file system.
3.assert-provide assertions.
1.http-creates http server.
2.fs-to handle file system.
3.assert-provide assertions.
Example code on how to use http module.
Below code creates a server to displays "Programming in Node.js" string.
var http=require('http');
http.createServer(function(req,res)
{
res.writeHead(200,{'Content-type':'text/plain'});
res.write("Programming in Node.js");
res.end();
}).listen(8080);
Apart from inbuilt node.js modules,developers can create their own modules and use them anywhere in the project and this makes the code reusable.
Creating a node.js module to return current date and time
var op=require('os');
exports.myOperatingSystem=function()
{
return op.platform();
}
save above code as "firstmodule.js"
var http=require('http');
var os=require('./firstmodule');
http.createServer(function(req,res)
{
res.writeHead(200,{'Content-type':'text/html'});
res.write("My Operating system is:" + os.myOperatingSystem() );
res.end();
}).listen(8080);
save the code as" firstscript.js"
Open a command prompt and run the file firstscript file.
Output
NB:
Any time you make changes to a node.js file, the changes don't reflect automatically to the server.To avoid restarting the server whenever making changes,
Try to Install