In Node.js, Modules are the blocks of encapsulated code that communicates with an external application on the basis of their related functionality. Modules can be a single file or a collection of multiples files/folders. The reason programmers are heavily reliant on modules is because of their re-usability as well as the ability to break down a complex piece of code into manageable chunks.
Modules are of three types:
- Core Modules
- local Modules
- Third-party Modules
Core Modules: Node.js has many built-in modules that are part of the platform and comes with Node.js installation. These modules can be loaded into the program by using the require function.
var module = require('module_name');
In the above example, the require() function returns an object because the Http module returns its functionality as an object. The function http.createServer() method will be executed when someone tries to access the computer on port 3000. The res.writeHead() method is the status code where 200 means it is OK, while the second argument is an object containing the response headers.
The following list contains some of the important core modules in Node.js:
|http||creates an HTTP server in Node.js.|
|assert||set of assertion functions useful for testing.|
|fs||used to handle file system.|
|path||includes methods to deal with file paths.|
|process||provides information and control about the current Node.js process.|
|os||provides information about the operating system.|
|querystring||utility used for parsing and formatting URL query strings.|
|url||module provides utilities for URL resolution and parsing.|
Local Modules: Unlike built-in and external modules, local modules are created locally in your Node.js application. Let’s create a simple calculating module that calculates various operations. Create a calc.js file that has the following code:
Since this file provides attributes to the outer world via exports, another file can use its exported functionality using the require() function.
Step to run this program: Run index.js file using the following command:
Addition of 50 and 10 is 60 Subtraction of 50 and 10 is 40 Multiplication of 50 and 10 is 500 Division of 50 and 10 is 5
Note: This module also hides functionality that is not needed outside of the module.
Third-party modules: Third-party modules are modules that are available online using the Node Package Manager(NPM). These modules can be installed in the project folder or globally. Some of the popular third-party modules are mongoose, express, angular, and react.
- npm install express
- npm install mongoose
- npm install -g @angular/cli