What is a Module in Node.js?

Author: neptune | 20th-Jun-2024
#Interview #Node.js

What is a Module in Node.js?

In Node.js, a module is a reusable block of code whose existence does not accidentally impact other code. Each module in Node.js has its own context, which means that the variables, functions, classes, etc., defined in a module are not visible outside of it unless explicitly exported.


Modules in Node.js are essential for organizing and structuring code, promoting code reuse, and separating concerns. They can be either built-in, third-party, or user-defined.


Types of Modules

1. Built-in Modules: These are modules provided by Node.js itself, like `fs`, `http`, `path`, etc.

2. Third-party Modules: These are modules created by the community and can be installed using npm (Node Package Manager).

3. User-defined Modules: These are custom modules created by developers for their specific application needs.


Creating and Using Modules

Creating a Module

To create a module, you simply write a JavaScript file and export the functionalities you want to be available to other files. 

    // mathOperations.js

    function add(a, b) {

        return a + b;

    }


    function subtract(a, b) {

        return a - b;

    }


    module.exports = { add, subtract };



In the above example, `mathOperations.js` is a module that exports two functions: `add` and `subtract`.


Using a Module

To use a module in another file, you import it using the `require` function.

    // app.js

    const math = require('./mathOperations');


    const sum = math.add(5, 10);

    const difference = math.subtract(10, 5);


    console.log(`Sum: ${sum}`); // Sum: 15

    console.log(`Difference: ${difference}`); // Difference: 5



Here, the `mathOperations` module is imported into `app.js` and its functions are used to perform arithmetic operations.


Built-in Modules

Node.js comes with several built-in modules that provide various functionalities. Some commonly used ones are:


1. fs: Provides an API for interacting with the file system.

2. http: Used to create HTTP servers and clients.

3. path: Utilities for working with file and directory paths.

Example of a Built-in Module

    // Using the 'fs' module to read a file

    const fs = require('fs');


    fs.readFile('example.txt', 'utf8', (err, data) => {

        if (err) {

            console.error(err);

            return;

        }

        console.log(data);

    });



Third-party Modules

These modules are installed via npm. For example, to use the `express` module, you would first install it using npm:


    npm install express



Then, you can use it in your application:

    // Using the 'express' module

    const express = require('express');

    const app = express();


    app.get('/', (req, res) => {

        res.send('Hello World!');

    });


    app.listen(3000, () => {

        console.log('Server is running on port 3000');

    });



Conclusion

Modules in Node.js are a powerful way to structure your application, promote code reuse, and keep your code clean and manageable. Whether you are using built-in modules, third-party modules, or creating your own, understanding how to work with modules is essential for any Node.js developer.




Related Blogs
Where you applied OOPs in Automation Testing?
Author: neptune | 28th-Aug-2023
#Interview #Java
You may face this question Where you have applied OOPs concept in Automation Framework? in almost all the Selenium Interviews. Let's learn OOP’s concept in Java before going further...

Mostly asked Python Interview Questions - 2023.
Author: neptune | 30th-May-2023
#Python #Interview
Python interview questions for freshers. These questions asked in 2022 Python interviews...

Core Python Syllabus for Interviews
Author: neptune | 26th-Jul-2023
#Python #Interview
STRING MANIPULATION : Introduction to Python String, Accessing Individual Elements, String Operators, String Slices, String Functions and Methods...

Top 50+ Selenium Interviews Questions 2023 based on Years of Experience
Author: neptune | 02nd-Apr-2023
#Selenium #Testing #Interview
Every interview difficulty is based on how many years of experience you have in that field. For the Selenium Automation Tester I have divided the question on the number of years of experience...

Top 10 Selenium Interview Questions with answers (2021).
Author: neptune | 02nd-Apr-2023
#Selenium #Interview
In this article I will cover top 10 Selenium interview questions...

30+ SQL Interview Questions
Author: neptune | 05th-Jan-2023
#Interview #SQL
Data Definition Language (DDL) – It allows end-users to CREATE, ALTER, and DELETE database objects...

25 Basic Java interview questions.
Author: neptune | 30th-May-2022
#Interview #Java
We will explore 25 basic Java interview questions...

Black Mirror Season 6: A Glimpse into the Future of Technology and Society
Author: neptune | 27th-Apr-2023
#Interview
Black Mirror Season 6, starring Salma Hayek and Aaron Paul, promises more violence and thought-provoking explorations of technology and society...

Top 20+ Appium Interview Questions and Answers (2023)
Author: neptune | 30th-May-2023
#Interview
This article provides a comprehensive list of 20 common interview questions on Appium mobile automation, covering various topics and providing solutions for each question...

Skills Required for Full-Stack Developer at IBM Onsite, CA
Author: neptune | 25th-Feb-2024
#Interview #Jobs
The company's commitment to pushing the boundaries of what is possible necessitates a team of skilled professionals...

Backend Developer Mock Interview | Interview Questions for Senior Backend Developers
Author: neptune | 28th-Jun-2024
#Interview #Node.js
Why did you choose this tech stack: React, React Native, Node.js, MongoDB, and Azure? We needed to create a cross-platform application...

How to Create an HTTP Server in Node.js ?
Author: neptune | 26th-Jun-2024
#Node.js
Node.js runs in a single process without creating a new thread for every request...

View More