Overview of Node.js Modules
Node.js modules are crucial for building scalable and maintainable applications. They help organize code and extend functionality through encapsulation, scalability, and ease of maintenance. Here’s a quick guide on using different types of Node.js modules:
Creating a Custom Module
Example: Arithmetic Operations
-
Create
arithmetic.js
:
// Define basic arithmetic functions
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
const multiply = (a, b) => a * b;
const divide = (a, b) => b !== 0 ? a / b : throw new Error("Cannot divide by zero.");
// Export functions
module.exports = { add, subtract, multiply, divide };
-
Use in
app.js
:
const arithmetic = require('./arithmetic');
console.log(arithmetic.add(5, 3)); // Output: 8
console.log(arithmetic.multiply(5, 3)); // Output: 15
Working with Core Modules
Commonly Used Core Modules:
-
fs
Module (File System): Read files asynchronously.
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log("File content:", data);
});
-
http
Module (HTTP Server and Client): Create a server.
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
server.listen(3000, () => console.log('Server running at http://localhost:3000/'));
Using Third-Party Modules
Example: Express Framework
- Install Express:
npm install express
- Setup Express Server:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World with Express!');
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Conclusion
Node.js modules streamline the development process by organizing code into manageable sections, promoting reusability, and leveraging both the core capabilities of Node.js and the vast ecosystem of third-party modules. Understanding and using these modules efficiently is key to building robust applications.
Top comments (0)