Thursday, February 20, 2020
Home Node.js What is a Module in Node.js and how to use it

What is a Module in Node.js and how to use it

Author

Date

Category

Module in Node.js is a simple or complex functionality organized in single or multiple JavaScript files that can be reused throughout the Node.js application. Each module in Node.js has its own context, so it cannot interfere with other modules or pollute the global scope. 

It is also a good practice to arrange the codes in such a way that makes it more manageable and maintainable for future purposes. That is where the Node.js module comes into the picture. Since each module is an independent entity with its own encapsulated functionality, it can be managed as a separate unit of work.

What is a Module?

Models in Node.js is the way to encapsulate the code in separate logical units. The best thing in Node.js is it has many ready-made modules available in the market which can be used within Node.js. Basically, there are three types of Node.js modules. They are:

  1. Core modules or Built-in Modules
  2. Local modules
  3. Third-party modules

1. Node.js core modules or Built-in Modules

The core modules include bare minimum functionalities of note.JS. These core modules are compiled into its binary distribution and loaded automatically when the Node.js process starts. However, you need to import the core modules first in order to use it in your application. Some important  built-in modules are mentioned below:

Modules Description
assert Provides a set of assertion tests
buffer To handle binary data
child_process To run a child process
cluster To split a single Node process into multiple processes
crypto To handle OpenSSL cryptographic functions
dgram Provides implementation of UDP datagram sockets
dns To do DNS lookups and name resolution functions
domain Deprecated. To handle unhandled errors
events To handle events
fs To handle the file system
http To make Node.js act as an HTTP server
https To make Node.js act as an HTTPS server.
net To create servers and clients
os Provides information about the operation system
path To handle file paths
punycode Deprecated. A character encoding scheme
querystring To handle URL query strings
readline To handle readable streams one line at the time
stream To handle streaming data
string_decoder To decode buffer objects into strings
timers To execute a function after a given number of milliseconds
tls To implement TLS and SSL protocols
tty Provides classes used by a text terminal
url To parse URL strings
util To access utility functions
v8 To access information about V8 (the JavaScript engine)
vm To compile JavaScript code in a virtual machine
zlib To compress or decompress files
assert Provides a set of assertion tests
buffer To handle binary data
child_process To run a child process
cluster To split a single Node process into multiple processes
crypto To handle OpenSSL cryptographic functions
dgram Provides implementation of UDP datagram sockets
dns To do DNS lookups and name resolution functions
domain Deprecated. To handle unhandled errors
events To handle events
fs To handle the file system
http To make Node.js act as an HTTP server
https To make Node.js act as an HTTPS server.
net To create servers and clients
os Provides information about the operation system

In order to use Node.js core or NPM modules, you first need to import it using require() function as shown below.

var module = require(‘module_name’);

As per the above syntax, specify the module name in the require() function. The require() function will return an object, function, property or any other JavaScript type, depending on what the specified module returns.

The following example demonstrates how to use Node.js http module to create a web server.

2. Node.js Local Modules

Local modules are modules created locally in your Node.js application. These modules include different functionalities of your application in separate files and folders. You can also package it and distribute it via NPM so that Node.js community can use it. For example, if you need to connect to MongoDB and fetch data then you can create a module for it, which can be reused in your application.

Writing a simple Module

Let us write a simple module that logs information and errors to the console. Always remember, while writing a Node.js module, the module should be placed in a separate .js file. So, let us create a Log.js file with the following code:

In the above example of a logging module, we have created an object with three functions – info(), warning() and error(). In the end, we have assigned this object to module.exports. The module.exports in the above example exposes a log object as a module.

The module.exports is a special object which is included in every JS file in the Node.js application by default. Use module.exports or exports to expose a function, object or variable as a module in Node.js.

Loading the Local Module

To use a Local module in our application, we had to load it using require() function in the same way we loaded the core modules. However, instead of writing the module name, you need to specify the path of the JavaScript file of the module. For example:

In the app.js,

Run the above example using the Terminal (or command prompt in Windows) as shown below.

node app.js

Output:

Info: Node.js started

3. Third party modules

The third party module can be downloaded by NPM (Node Package Manager). These type of modules are developed by others and we can use that in our project. Some of the best third party module examples are listed as follows: express, gulp, lodash, async, socket.io, mongoose, underscore, pm2, bower, q, debug, react, mocha etc. Third party modules can be install inside the project folder or globally.

We will keep updating this article all along, and we will keep adding more tutorials and fundamental things about Node.js to it. So don’t forget to subscribe to our Newsletter.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Subscribe to our newsletter

Snehasish Nayak
I am Snehasish Nayak, a Senior Programmer at NIC, Bhubaneswar and a Google Product Expert.

Recent posts

Recent comments