n Node.js, modules are reusable pieces of code that help organize and maintain projects efficiently. They allow us to break code into smaller, manageable parts.
Core Modules (Built-in)
These are modules provided by Node.js and can be used without installation.
Example: Using Core Modules
const fs = require(“fs”); // File System module
fs.write File Sync (“example.txt”, “Hello, Node.js!”); // Writing to a file
console.log(“File written successfully!”);
Other Common Core Modules:
- http → Create an HTTP server
- fs → Handle file system operations
- path → Work with file and directory paths
- os → Get system-related information
- events → Handle event-driven programming
- Local Modules (User-Defined)
Local Modules (User-Defined)
These are custom modules created by developers to organize code.
Example: Creating and Using a Local Module
math.js (Custom Module)
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a – b;
}
module.exports = { add, subtract }; // Export functions
app.js (Using the Custom Module)
const math = require(“./math”); // Import local module
console.log(math.add(5, 3)); // Output: 8
console.log(math.subtract(5, 3)); // Output: 2
Note: Local modules must be required using ./ (relative path).
3. Third-Party Modules (Installed via npm)
These are modules installed from the npm (Node Package Manager) registry.
Example: Installing and Using axios (HTTP Requests)
Step 1: Install the module
npm install axios
Step 2: Use the module
const axios = require(“axios”);
axios.get(“https://jsonplaceholder.typicode.com/todos/1”)
.then(response => console.log(response.data))
.catch(error => console.error(“Error fetching data:”, error));
Popular Third-Party Modules:
- express → Web framework
- mongoose → MongoDB object modeling
- jsonwebtoken → Handling JWT authentication
- dotenv → Manage environment variables
File Handling
- Node.js provides built-in modules for file handling.
- The fs (File System) module allows interacting with the file system.
Importing the fs Module
const fs = require(‘fs’);