In node.js, module is a JavaScript file and it will contain a set of functions to reuse it in node.js applications.
In node.js, each file is treated as separate module and the modules in node.js are same like JavaScript libraries.
In node.js, modules are useful to move the common functionalities to separate .js file to reuse it in applications based on our requirements. In node.js, each module has its own context, so if we create any new module that won’t interfere with other modules in application.
In node.js, we can include or import a module by using require
directive with module name like as shown below.
// importing node.js built-in http module
var http = require('http');
We imported an http
module by using require
directive. Now our application is having an access to HTTP module so we can create a server to listen a request and response on particular port number like as shown below.
// creating server
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Welcome to Tutlane');
res.end();
}).listen(4200);This is how we can include or import a modules in our node.js applications.
In node.js, modules are divided into three primary categories, those are:
By default, the node.js comes with a set of built-in modules and these are useful while implementing an application.
Generally, the built-in or core modules are installed on our machine during the node.js installation and those will load automatically when node.js process starts. To use built-in modules in our node.js application, we need to import it using require
directive like as mentioned above.
Following table lists some of the important built-in / core modules available in node.js.
Module | Description |
---|---|
http | It is useful to create an HTTP server in node.js. |
url | It provides utilities for URL resolution and parsing. |
querystring | It provides a functionalities to parse and format URL query strings. |
path | It is useful to deal with file paths. |
fs | It is useful to handle file system related operations like read, write, open, etc. |
crypto | It is useful to work with cryptographic functionalities like cipher key, decipher, sign, etc. |
net | This module provides an asynchronous network API for creating stream-based TCP or IPC servers. |
dns | It is useful for domain name resolutions and DNS queries. |
os | It is helpful to work with operating system related utility methods. |
Following is the example of using a built-in / core http
module in node.js applications. Now, create a file called Helloworld.js and write the code like as shown below.
// importing node.js built-in http module
var http = require('http');
// creating server
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello World!');
res.end();
}).listen(4200);
If you observe above code, we imported an http
module by using require
directive to access HTTP module and created a server to listen the request and response on port number 4200.
Here, the above code will tell the computer to write “Hello World” if anyone tries to access your computer on port 4200.
Now, open node.js command prompt and navigate to the folder that contains a Helloworld.js file and initiate it by entering a command like as shown below.
Now your computer will work as server so if anyone tries to access your computer with port 4200, then in return they will get a “Hello world” message like as shown below.
In node.js, the external modules are implemented by node.js community people to solve the lot of common coding problems without rewriting the same code for every application.
Generally, these external modules are published in Node Package Manager (NPM) registry, so to use external modules in our application first, we need to install the external module codebase from NPM locally using Npm install module_name
command.
Once we install the codebase locally from NPM, then we can import it in our application using require(‘module_name’)
function.
Following table lists some of the widely downloaded external/third party modules from NPM in node.js.
Module | Description |
---|---|
bower | It will make sure all application packages are up to date. |
csv | It provides the functionality to generate CSV file dynamically, modify it, transforming CSV, etc. |
debug | It’s a utility which consist core debugging methods. |
gulp | To make automation for your web app to resolve workflow. |
lodash | It provides an extensive set of functions to achieve high performance with fewer lines of code. |
mongoose | It is useful to work with object modeling tools. |
mongodb | It's an official MongoDB driver for the nodejs application. |
In node.js, the built-in and external modules are created by others to fulfill some common functionalities, but it's not limited that we should use only those packages/modules.
In node.js, we can also create our own custom module and use it in our application by just importing it.
Following is the example of creating a module called custommodule to perform arithmetic operations like addition, multiplication, subtraction, and division.
Now, create a file called custommodule.js and write the code like as shown below.
// Creating function for adding two values
exports.Addition = function(val1, val2)
{
return (val1 + val2)
}
// Creating function for subtracting two values
exports.Subtract = function(val1, val2)
{
return (val1 - val2)
}
// Creating function for multiplying two values
exports.Multiplication = function(val1, val2)
{
return (val1 * val2)
}
// Creating function for dividing two values
exports.Division = function(val1, val2)
{
return (val1 / val2)
}
Here, we created our own custom module (custommodule) with different functions and used an exports
keyword to make our properties and methods available outside the module file.
In node.js, we can include or import our custom module same like built-in or external modules by using require
directive with module name like as shown below.
Now, create a file called mathoperations.js and write the code like as shown following to include our custom module (custommodule) in node.js application.
// Import bulit-in and custom modules
var http = require('http');
var cm = require('./custommodule');
//Create server
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Addition: ' + cm.Addition(25,50) + '</br>');
res.write('Subtraction: ' + cm.Subtract(25,50) + '</br>');
res.write('Multiplication: ' + cm.Multiplication(25,50) + '</br>');
res.write('Division: ' + cm.Division(25,50));
res.end();
}).listen(4200, console.log('Server running on port 4200'));
If you observe above example, we used a ./
to locate our custom module (customodule) in require
function, that means the custom module (custommodule.js) exists in the same folder where mathoperations.js file exists.
Now open node.js command prompt, navigate to the folder where the files exist and enter a command like node mathoperations.js
and click enter like as shown below.
Now our computer will work as a server, so if anyone tries to access our computer with http://localhost:4200 URL, then in return they will get a result like as shown below.
This is how we can create and import custom modules in our node.js applications based on requirements.