Introduction to Node.js Modules
Understand what modules are in Node.js, why we use them, how modules organize application code, and how different JavaScript files can share functionality.
1. What Are Modules in Node.js?
A module is a reusable unit of code that contains related functions, variables, classes, or other functionality. Modules help us divide a large application into smaller, manageable files.
Imagine developing a student management application. The application may need to manage student details, calculate fees, validate data, and generate reports. Instead of writing everything in one file, we can organize these responsibilities into separate modules.
For example:
student.jscan contain student-related functions.fees.jscan contain fee calculation functions.validation.jscan contain validation logic.app.jscan coordinate the application's operations.
2. Why Do We Need Modules?
When an application grows, maintaining all its code in a single file becomes difficult. Modules allow developers to separate responsibilities and work with smaller pieces of code.
Advantages of Modules
- Code Reusability: A function can be shared with other files instead of being rewritten.
- Better Organization: Related functionality can be grouped into separate files.
- Easy Maintenance: A specific feature can be updated without searching through one large file.
- Readability: Smaller files make the application easier to understand.
- Team Collaboration: Developers can work on different modules independently.
- Separation of Responsibilities: Each module can focus on a particular task.
3. Node.js Module Architecture
In a modular application, different files handle different responsibilities. The main application imports or loads the required functionality and uses it when needed.
app.js
Coordinates the application and uses required modules.
Student information and operations
Fee calculations
Data validation
Each module manages its own responsibility and exposes functionality that other files may use.
This structure makes it easier to understand which file is responsible for a particular task. The exact way functionality is shared depends on the module system being used.
4. Types of Modules in Node.js
Node.js applications commonly use three categories of modules: built-in modules, custom modules, and third-party modules.
| Module Type | Description | Examples |
|---|---|---|
| Built-in Modules | Modules supplied by Node.js. |
fs, path,
os, http
|
| Custom Modules | Modules created by developers for their applications. |
student.js, fees.js
|
| Third-party Modules | Packages created and distributed by other developers. |
express, mongoose
|
5. CommonJS Module System
CommonJS is a module system traditionally used
by Node.js. It commonly uses require() to load a
module and module.exports or
exports to expose functionality.
Example: Export a Function
Create a file named math.js and define an addition
function inside it.
function add(a, b) {
return a + b;
}
module.exports = add;
Import and Use the Function
Create another file named app.js. Load the exported
function using require().
const add = require("./math");
const result = add(10, 20);
console.log("Addition:", result);
Expected Output
Addition: 30
Explanation
math.jsdefines theadd()function.module.exports = addexposes that function.require("./math")loads the exported value.add(10, 20)executes the imported function.- The result is displayed using
console.log().
6. ES Modules
ES Modules (ESM) are the standard JavaScript
module system. They use the export keyword to
expose functionality and the import keyword
to use exported functionality.
Export a Function
export function add(a, b) {
return a + b;
}
Import and Use the Function
import { add } from "./math.mjs";
console.log("Addition:", add(15, 25));
Expected Output
Addition: 40
These examples use the .mjs extension to identify
ES modules explicitly. Node.js also supports ES modules in
appropriately configured .js files.
require() and module.exports, whereas
ES Modules use import and export.
7. How Import and Export Work
Exporting makes functionality available to another module. Importing or requiring loads that functionality so the current file can use it.
math.js
function add(a, b)
Defines the function.
Expose Functionality
module.exports = add
Makes the function available to another CommonJS module.
app.js
const add = require("./math")
Loads the exported function.
Use the Function
add(10, 20)
The result is 30.
This diagram illustrates the CommonJS approach. ES Modules use
the same general idea of sharing functionality, but use
export and import syntax.
8. CommonJS vs ES Modules
| Feature | CommonJS | ES Modules |
|---|---|---|
| Load or import | require() |
import |
| Export | module.exports or exports |
export or export default |
| Typical file extension | .cjs or CommonJS-configured .js |
.mjs or ES-module-configured .js |
| Module style | CommonJS module system | Standard JavaScript module system |
| Example | const fs = require("node:fs") |
import fs from "node:fs" |
9. Built-in Modules Overview
Node.js provides built-in modules for common tasks. These modules can be used without separately installing a package.
| Module | Purpose |
|---|---|
fs |
Work with files and directories. |
path |
Work with file and directory paths. |
os |
Access operating-system information. |
http |
Create HTTP servers and handle HTTP requests. |
events |
Work with event-driven programming. |
url |
Parse and work with URL information. |
These modules will be covered individually in upcoming Node.js tutorial topics.
10. Common Mistakes
| Mistake | Correct Understanding |
|---|---|
| Trying to import a function that was not exported. | Ensure the required function or value is exported. |
| Using the wrong file path. | Check the relative path and filename. |
| Mixing CommonJS and ES Module syntax without understanding the configuration. | Check the module system used by the project. |
| Assuming every module must be installed separately. | Node.js already provides built-in modules. |
| Writing all application logic in a single file. | Separate related responsibilities into modules when appropriate. |
11. Practice Tasks
Task 1: Create a Calculator Module
Create calculator.js and define functions for
addition and subtraction. Export the functions and use them
in app.js.
Addition: 30
Subtraction: 10
Task 2: Create a Student Module
Create a module that exports a function returning a student's name and course. Import the function into another file and display the result.
Expected Output:Student: Samadhan
Course: Node.js
Task 3: Try ES Modules
Create a module that exports a multiplication function using
export. Import it into another ES module using
import.
Multiplication: 200
Summary
Node.js modules organize application code into reusable and manageable units. Built-in modules provide functionality for common tasks, custom modules allow developers to separate their own application logic, and third-party modules provide additional features. CommonJS uses require() and module.exports to load and share functionality, while ES Modules use import and export. Using modules improves code reusability, readability, maintainability, and application organization.