Example include a modules in nodejs

Example:

1. Create a module get current date and save

 C:\Nodejs\getDate.js

 

exports.myDateTime = function () {

    return Date();

};

 

2. create http server and save

C:\Nodejs\useModule.js

 

//use module http

var http = require('http');

// use module getDate

var dt = require('./getDate');

http.createServer(function (req, res) {

    res.writeHead(200, {'Content-Type': 'text/html'});

    res.write("The date and time are currently: " + dt.myDateTime());

    res.end();

}).listen(8080);

 

Run program with cmd:

 

C:\Nodejs>node useModule.js

 

Go browser http://localhost:8080/

 

The date and time are currently: Tue Apr 10 2018 16:49:14 GMT+0700 (SE Asia Standard Time)

 

Notice that we use ./ to locate the module, that means that the module is located in the same folder as the Node.js file.