Node.js Modules

A Node.js Module is a library of functions that could be used in a Node.js file.

Node.js Modules

There are three types of modules in Node.js based on their location to access. They are :

  1. Built-in Modules

    These are the modules that come along with Node.js installation.
    Reference to the list of Node.js Built-in Modules.

  2. User defined Modules

    These are the modules written by user or a third party.
    We shall learn more in detail about user defined modules in the Node.js User Defined Modules section.

  3. Thrid party Modules

    There are many modules available online which could be used in Node.js. Node Package Manager (NPM) helps to install those modules, extend them if necessary and publish them to repositories like Github for access to distributed machines.

    • Install a Node.js module using NPM
    • Extend a Node.js module
    • Publish a Node.js module to Github using NPM

 

Include a module

Including a module in the Node.js files allows us to use the functions exposed by the module.

Syntax

Following is the syntax to include a module in a Node.js file.

var http = require(‘<module_name>’);

Example

To include ‘http’ module in a Node.js file, we need to write the below require statement before using the http module.

var http = require(‘http’);

 

Using function of a module

Once you have included a module by assigning it to a variable, the functions in the module could be accessed through the variable.

In the above module section, an example for including http module is provided. Now we shall use a function of http module called createServer() to demonstrate on how to use a function of a module.

The function creates an HTTP Server that responds with ‘Node.js says Hello!’ when an http request is made to port 8080.

 

Conclusion :

In this Node.js Tutorial, we have learnt about Node.js Modules, how to include them in a Node.js file, and how to use a function of a Node.js Module.