Modules📤📥 in Node.js : Beginner to Advance💻
Tags: webdev, javascript, node, beginners
Published: 2023-07-20 19:16:51

_Both `Browser's javascript` (ECMAScript Modules (ESM)) and `Node.js's javascript` support modules, but there is a difference in syntax. After reading and gaining insightful knowledge about modules in node.js, you can read difference between them_.

So, let's get started😃.

## ✒️Modules : Definition

> _Modules enable you to `structure` and `contain your code within distinct files and folders`, enhancing its organization and `reusability`. By employing modules, you can break down your application into smaller units, each serving a specific purpose. These units can then be integrated to construct a comprehensive and functional application. They are, in Node.js are fundamental components that play a crucial role in this JavaScript runtime, utilizing Chrome's V8 engine._

In simple language, We can use functionality of one file into another file, and vise versa.
 

## ✒️Types of Modules in Node.js :

1. **Core Modules**: These are built-in modules provided by Node.js, which can be used without requiring any additional installation. Examples include `fs` (file system), `http` (HTTP server and client), `os` (operating system), and more.
2. **Local Modules**: These are modules you create within your application. They are usually organized into separate files and folders to keep the codebase clean and maintainable.
3. **Third-party Modules**: These are modules created by the `Node.js community` and available through the `Node Package Manager (NPM)`. NPM is a package manager that allows developers to share and reuse code easily. You can use third-party modules in your projects by installing them using NPM.

---

## 📤Exporting from a Module:
 
To make functions, variables, or classes available from a module to other parts of your application, you need to export them. Node.js provides different ways to export items from a module:

- **Named Exports**: Export individual items one by one using `exports` or `module.exports`.
- **Default Export**: Export a single item (typically an object or a function) as the default export using `module.exports`.

> _Note : We will see named and default exports in later part of this tutorial._

## 📥Importing a Module:
 
To use functionality from other modules in your current module, you need to import them. Node.js provides the require() function to import modules:

- **Core Modules**: Imported without any path (e.g., const fs = require('fs')).
- **Local Modules**: Imported using relative paths (e.g., const myModule = require('./myModule')).
- **Third-party Modules**: Imported just like local modules if they are installed using NPM.

Too much theory😅!!!!!, Let's understand with example😃.

**Step 1:** Create the module

Create a new file named `mathCalOperations.js`:

```
// mathCalOperations.js

//ARROW FUNCTION
const add = (a, b) => {
  return a + b;
};

//NORMAL FUNCTION
function subtract(a, b) {
  return a - b;
};
//BOTH STYLE ARE ACCEPTABLE

const multiply = (a, b) => {
  return a * b;
};

const divide = (a, b) => {
  if (b === 0) {
    throw new Error('Divide by zero error, Cannot divide by zero!');
  }
  return a / b;
};

const PI = 3.14159;

module.exports = {
  add,
  subtract,
  multiply,
  divide,
  PI,
};

```
In this module, we have separate functions add, subtract, multiply, and divide, along with a constant PI.

**Step 2:** Import and use the module

Create a new file named `app.js`:

```
// app.js
const cal = require('./mathCalOperations');

const num1 = 10;
const num2 = 5;

console.log(`Addition: ${cal.add(num1, num2)}`);
console.log(`Subtraction: ${cal.subtract(num1, num2)}`);
console.log(`Multiplication: ${cal.multiply(num1, num2)}`);

try {
  console.log(`Division: ${cal.divide(num1, num2)}`);
} catch (error) {
  console.error(error.message);
}

console.log(`Value of PI: ${cal.PI}`);

```
In this file, we use the `require()` function to import the `mathCalOperations.js` module. We call the functions add, subtract, multiply, and divide to perform arithmetic operations on the numbers num1 and num2, and we also access the constant PI.

**Step 3:** Run the application

Save both files in the same directory and run `app.js` using Node.js:

```
$ node app.js

```
**Output :**

```
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
Value of PI: 3.14159

```
The `mathCalOperations.js` module is successfully imported into `app.j`s, and we used its separate functions and the constant PI to perform mathematical operations and access the value of PI.
This example demonstrates how to create a module with separate functions and variables, export them using `module.exports`, and import and use them in another JavaScript file using `require()`.

At the end, we are returning an `object { }`as there are many functions and variable, object is a best way to combine (you can also use class).

_What if you write a object and return it._

So we can above program like this.

```
// mathCalOperations.js
const cal = {
    add: (a, b) => {
    return a + b;
  },
  subtract: (a, b) => {
    return a - b;
  },
  multiply: (a, b) => {
    return a * b;
  },
  divide: (a, b) => {
    if (b === 0) {
      throw new Error('Divide by zero error, Cannot divide by zero!');
    }
    return a / b;
  },
};

module.exports = cal;

```
_Here, We are making object from start and returning it, while in previous one, We were making `object{}` at end._

**📍Note : `Module.exports` is an object.**
It is a special object used to define what a module exports, i.e., what functionalities or data it makes available to other parts of the application.
If you send just a function or a variable in Node.js using `module.exports`, it will work perfectly fine. In Node.js, `module.exports` can hold any value, not just objects.
So, `module.exports` is an object, and with it we can send any type. 

---
So, Here we end😃.
In, **📤Exporting from a module section**, We left Named and Default exports.
Let's continue that.
 

## 📌Named Exports:

> _Named exports allow you to export multiple items (functions, variables, or classes) from a module and import them individually by their names in other parts of your application. When you use named exports, you explicitly specify which items you want to make available for importing_.

**mathCalOperations.js:**


```
// mathCalOperations.js
const add = (a, b) => {
  return a + b;
};

const subtract = (a, b) => {
  return a - b;
};

module.exports.add123 = add;
module.exports.subtract123 = subtract;

```
In this example, we have two functions add and subtract in the `mathCalOperations.js` module. We export them using the `module.exports` object with the property names add and subtract. This makes the functions individually accessible when importing the module in another file.

**app.js:**

```
// app.js
const cal = require('./mathCalOperations');

const num1 = 10;
const num2 = 5;

console.log(`Addition: ${cal.add123(num1, num2)}`);
console.log(`Subtraction: ${cal.subtract123(num1, num2)}`);

```
In app.js, we import the `mathCalOperations.js` module and store it in the `cal` variable. We can then access the exported functions add and subtract using `cal.add123()` and `cal.subtract123()` respectively.

## 📌Default Export:

> _A default export allows you to export a single item (usually an object, a function, or a class) as the main export of the module. When using a default export, you can import the item using any name you want, making it more flexible when importing._

**greeting.js:**

```
// greeting.js
const greet = (name) => {
  return `Hello, ${name}!`;
};

module.exports = greet;

```
**app.js:**

```
// app.js
const customGreeting = require('./greeting');

const name = 'John';
console.log(customGreeting(name));

```
In app.js, we import the greeting.js module and store the default exported function in the variable customGreeting. Since it is a default export, we can give it any name we want. We then call the function using customGreeting(name) to get the greeting message.

The first example of this tutorial, _above at top_ is also an example of `Default Export`.

It's not the end, I will add few more about it, later in future😊.

Happy Learning!! , Until next time🫂.
If you liked the article, do hit like😃.