What are Modules in Nodejs? Its Types with Examples.

KHEEM DHARMANI
3 min readAug 3, 2021

The Nodejs is totally based on a modules system. And in NodeJs every file considers as a module. So, the modules are JavaScript files that contain different functions with different functionality.

Modules may contain single files or they may have multiple files and folders. The Nodejs programmers prefer to use modules because of code reusability and by using modules the complex code implement into chunks.

How many types of modules in NodeJs?

There are three main types of Nodejs modules.

  • Core Modules (Built-in Module)
  • Local Modules
  • Third-Party Modules

We now discuss each type separately with appropriate examples.

  • Core Modules (Built-in Module)

They are also known as built-in modules because they come with Nodejs installation. We just need to require them in our code. Nodejs has a rich library for core modules, by using these you can build highly scalable web applications.

Examples:

Core Modules Examples

In the above picture, we used the most common core modules. For their description see the comments in front of each code line. To use core modules you do not need to install explicitly, you just need to require them and store them into their respective variable name.

2. Local Modules

They are also known as your own modules. Yes, local modules mean that you create your own module and then require it in your code.

How You Create Local Modules?

You have to create a new file in your code editor with .js extension. And write your code as your project requirements. And then require this file in your main index.js file. By creating and using your own modules helps to shorten the code and also call these modules where you want.

Example:

Create Local Module

Created a local module with filename [local_module.js]. Here you have to use the keyword module.exports, by doing so it will make to call outside.

Require Local Module
Now, you have to go to the main index.js file of your project and create a new variable[my_local_module] and require it by its filename[local_module] just before we created it.

3. Third-Party Modules:

The third-party modules are stored on the popular website NPM. They are available online and you can install them in your code as your project requirement. Express, React, Mongoose, and Slugify are most popular modules of the Node Package Manager. You can simply install by using syntax.

npm install [module_Name]

Example:

To install express you write command in your prompt :

npm install express

Now you can use installed modules by requiring them in your project.

const express = require(‘express’);

Is This Helpful?

--

--

KHEEM DHARMANI
0 Followers

As a highly skilled and experienced in content writing, with more than 5 years of academic studies.