Open In App

What are Modules in Node.js ?

Last Updated : 18 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Node.js Application, a Module can be considered as a block of code that provide a simple or complex functionality that can communicate with external application. Modules can be organized in a single file or a collection of multiple files/folders. Almost all programmers prefer modules because of their reusability throughout the application and ability to reduce the complexity of code into smaller pieces. 

Nodejs uses the CommonJS Module standard implementation in its module ecosystem. 

Types of Modules:  In Nodejs, there is 3 type of modules namely

  • Core Modules
  • Local Modules 
  • Third-Party Modules

Core Modules:  Node.js comes with dozens of built-in modules. These built-in modules are sometimes referred to as core modules. The module system is built around the require function. This function is used to load a module and get access to its contents. require is a global variable provided to all your Node.js scripts, so you can use it anywhere you like. require() function will return a JavaScript type depending on your module.

Syntax for Importing Module: 

const module = require("Name_of_Module_to_be_imported");

How to use Core Module: You can directly use the Nodejs core module in your application without any installation. Let’s see an example of the file system (fs) module to handle the files in the application. 

Initially, the Project Directory will look like this: 

Initially, the Project directory

Example: Write the below code in the index.js file 

Javascript




// Working code of fs module
const fs = require('fs'); // Import fs module
fs.writeFileSync('notes.txt', 'I love to code');


The script above uses require to load in the fs module. This is a built-in Node.js module that provides functions you can use to manipulate the file system. The script uses writeFileSync to write a message to notes.txt.

To run the script use the following command on your terminal

$ node index.js

After you run the script, you’ll notice a new notes.txt file in your directory. Open it up and you’ll see, “I love to code”.

Output: Now we have a new file notes.txt in our directory. And “I love to code” written has written on it.

Output 

Here is the list of some Nodejs Core Modules: 

Core Modules Name Description 
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.
os It provides information about the operation system.
path To handle file paths.
cluster To split a single Node process into multiple processes.
dns To do DNS lookups and name resolution functions.
tls To implement TLS and SSL protocols.
querystring To handle URL query strings.
url To parse URL strings.
events To handle events
timers To execute a function after a given number of milliseconds.

Local Modules: Putting all your code in a single file is not a good idea. As you add more code, you’ll want to stay organized and break your Node.js app into multiple scripts that all work together. For that purpose, we can create local modules in our application. 

Exporting from files: Firstly we need to create a file called utils.js. Now We can export javascript code written on this file using module.exports. In below a function is defined and assigned to the module.exports. 

Project setup:

 

  • Utils.js: Write the below code in the utils.js file

Javascript




const tests = function() {
    console.log("Yehh! Local file is running successfully...");
}
module.exports = tests;


Importing your own files:  Now we need to import the local file into index.js. require function is also used for importing the files in the directory. All you need to do is provide require with a relative path to the script you want to load. This path should start with ./ and then link to the file that needs to be loaded.

Filename:- In the index.js file

Javascript




const utility = require('./utils.js');
utility();


The code above uses require to load in a file called utils.js in the src directory. It stores the module contents in a variable, and then use the contents in the script. 

If you run the above index.js script. you will see the message that is logged from the tests function defined in the utils.js file.

Output: 

Yehh! Local file is running successfully...

 

Third-party Modules:  Third-party modules can be installed from the NPM (Node Package Manager) available online. 

Firstly we need to initialize the npm using the npm init command before npm can be used. It creates a package.json file in the root directory and it stores all the information about the third-party module that we have installed as a dependency. 

Installing an NPM module:

npm install "module_name"

The above command will do the following:

Firstly, It creates the node_modules directory which npm uses to store all the codes of the npm module you have installed. Secondly, npm add a module as a dependency by listing it in the dependencies property in the package.json file, and lastly, npm creates a package-lock.json file. This is used to store information about the modules you’ve installed which helps keep things fast and secure. 

 

Examples of Third-Party Module: 

  • npm install express
  • npm install lodash
  • npm install mocha

Let’s see with an example how to use third party modules: 

  • validator is a popular module used for string validations and sanitizations.

To install run the following command:

$npm install validator

 

npm modules can be imported into your script using require. To load in an npm module, pass the npm module name to require:

index.js: Write the below code in the index.js file

Javascript




const validator = require("validator");
// Print: true
console.log("URL is " + validator.isURL("https://google.com"));
// Print: false
console.log("Email is " + validator.isEmail("johndoeeg.com"));


Output: 

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads