Search anything:

Introduction to Modules in Node.js

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

Reading time: 15 minutes

In this article, we will go through the three types of modules in Node.js namely in-built, third party and local modules and explore them with examples.

⭐ Introduction to Node.js modules -


In Node.js modules system, every file is treated as a module.
Consider a file named index.js which contains the following code -

const square = require('./square.js');
console.log(`The area of a square of length 4 is ${square.area(4)}`);

Here, in the first line, module named square.js is loaded, which is present in the same directory as the index.js.
The contents of square.js are -

exports.area = (length)=>length*length

Here, square.js has exported its function, area() using the exports keyword, to make it available to other modules.

⭐ Types of Modules in Node.js -

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

We will be exploring each category with relevant examples.

⭐ 1. Built-in Modules

Built-in modules are the predefined modules in Node.js that need no installation , and can be used anywhere in the application.

Some of the built-in modules are fs, https, url, path, util, etc.
These core modules include bare minimum functionalities of Node.js.Though these modules are loaded automatically when Node.js process starts, we need to include them in our working module first to use it.

So, let's start with the fs(File System) module.fs module provides an API to interact with the files on our system. Common uses of the fs module is to

  • Create files
  • Rename files
  • Update files
  • Delete files
  • Read files

Let's learn more about the fs module.

So, create a directory named node-example, and create a file named index.js and dataIn.txt inside it. Open the directory in your editor.

📝 Step 1: Include the module

To include the fs module, use the require() function with the name of the module, and initialize it to a variable.

const fs = require ('fs')

Now, we have access to all the functionalities of the File System module through the variable fs.

📝 Step 2: Use the module - read and write to a file

Now, that we have installed the module in our file, let's use it to read a file and write to a file.

📁 Reading file -

Open dataIn.txt in your editor and write down the following lines in it -

Apples are made of 25% air, which is why they float.

That's a cool fun food fact though. 🍎
The method used to read file synchronously is - readFileSync(). It takes in two parameters - file path, and character encoding.

Write the following code in your index.js

const textRead = fs.readFileSync("dataIn.txt", "utf-8");

Save your file and Open your terminal and run node index.js

You will see the output on the terminal.


📁 Writing to a file -

We use the method writeFileSync() to write to a file synchronously. It takes in two parameters - file path, text to be written.

Include the following code in index.js -

const textWrite = "Originally, coffee was eaten as energy balls! :?";
fs.writeFileSync("dataOut.txt", textWrite);
const data = fs.readFileSync("dataOut.txt", "utf-8");

You will see the following output on terminal :


Note : In case of writing to a file, fs creates the file itself if not found. You may notice that dataOut.txt is now present in your directory.

⭐ 2. Local Modules

Local modules are the modules that we build locally for our application. These modules contain different functionalities of our application.

So, let's create a module that will take a year of birth as input and will display our age.

📝 Step 1 : Create the local module -

So, create a file called ageCalc.js in the same directory.
And include the following code to calculate your age from your dob.

module.exports = dob => {
  return new Date().getFullYear() - dob;

Note :In each module, we have access to a variable called module and on it, we can set the exports property to make it available to other modules.

📝 Step 2 : Including the local modules -

Get back to index.js, and it's time to include ageCalc.js in our code. The syntax remains the same, like that for the built-in modules.

const calcAge = require("./ageCalc");

The function that we exported from ageCalc.js, now resides in calcAge.

📝 Step 3 : Use the module

It is very simple to use the function now, we can call it like any other function present inside index.js. So go ahead, and include the following code in your index.js.

const myAge = calcAge(1999);
console.log(`My age is ${myAge}`);

Save the files, and now when you run node index.js in your terminal, you may see the following output -


⭐ 3. Third party modules

Third-party modules are developed by others and can be downloaded by Node Package manager(npm). These kinds of modules are not predefined in Node.js and need to be installed explicitly. We can download such modules locally in our project, or globally for the system.
Some of the best third-party module examples are nodemon, express, gulp, lodash, async, socket.io, mongoose, underscore, pm2, bower, q, debug, react, mocha, etc.

In this example, we will be using nodemon.

nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.

So, we need not run node index.js every time we save our changes in the file. nodemon runs itself after we save any changes to our file.

📝 Step 1 : Install the module

We will be installing nodemon globally since it is useful in almost all Node.js applications, and also installing it globally will let us use nodemon as a command-line utility.

Open your terminal and use the command:

npm install -g nodemon

to install it.

📝 Step 2 : Using nodemon

After nodemon has been installed successfully, use the command nodemon index.js. Now, let's observe our terminal. Initially the terminal looks like this -


As you may notice, it is waiting for some changes to take place to restart the application. Now, add the following line to your index.js

console.log("Hurray! Nodemon works :)");

And save the file. As soon as you save it, you can see the new output on the terminal. This happens because of nodemon.


And this is how nodemon and several other 3rd party packages can make our work so easier.

⭐ References/ Further Reading -

You may read more about Node.js modules here.

Priyanka Yadav

Priyanka Yadav

Full Stack JavaScript Developer | Cloud and Devops Enthusiast | Bachelor of Technology (2017 to 2021) in Computer Science at University of Petroleum and Energy Studies | Intern at OpenGenus

Read More

Improved & Reviewed by:

OpenGenus Tech Review Team OpenGenus Tech Review Team
Introduction to Modules in Node.js
Share this