Saturday, 11 November 2017

Node.js | What is a Module in Node.js?

The module in Node.js is a simple or complex functionality organized in single or multiple JavaScript files which can be reused throughout the Node.js application. It is same as JavaScript libraries. It contains a set of functions we want to include in our application.

Module Types
Node.js includes three types of modules:
3. Third Party Modules

Built-in Modules
Node.js has a set of built-in modules which you can use without any further installation.

Include Modules
To include a module, use the require() function with the name of the module:

var http = require('http');

Now our application has access to the HTTP module, and is able to create a server:
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('Hello World!');

Create Your Own Modules
We can create our own modules, and easily include them in our applications. Create a module that returns the current date and time:
exports.myDateTime = function () {
    return Date();

Use the exports keyword to make properties and methods available outside the module file. Save above code in a file named as "myModule.js"

Include our Own Module
We can include the module by using the require function in any of our Node.js files.

var http = require('http');
var dt = require('./myModule');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write("Current date is "+dt.myDateTime());

Output: Current date is Sat Nov 11 2017 19:40:17 GMT+0530 (India Standard Time)

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...