- 6 months ago
- Zaid Bin Khalid
- 475 Views
-
2
In Node.js, modules are encapsulated units of code that can be reused across different parts of an application. They help organize code into separate files or packages, improving maintainability and enabling better code reuse. Node.js follows the CommonJS module system, which allows modules to export functions, objects, or primitive values for use in other modules.
Types of Modules in Node.js:
- Core Modules:
- These are built-in modules provided by Node.js.
- Examples include
fs
(file system operations), http
(HTTP server/client), path
(path-related utilities), etc.
- Core modules are loaded using
require()
without specifying a path (e.g., const fs = require('fs');
).
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
- Local Modules:
- These are modules created within your Node.js application.
- They are files created by the developer to organize code into reusable components.
- Local modules are loaded using
require()
with a relative or absolute path to the file. Example of a local module (math.js
):
// math.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = { add, subtract };
Using the local module in another file (app.js
):
// app.js
const { add, subtract } = require('./math');
console.log(add(5, 3)); // Output: 8
console.log(subtract(5, 3)); // Output: 2
- Third-Party Modules:
- These are modules created by third-party developers and shared via npm (Node Package Manager).
- They extend Node.js functionalities beyond what core modules offer.
- Third-party modules are installed via npm and then loaded using
require()
similar to local modules. Example using a third-party module (axios
for HTTP requests):
// Install axios via npm: npm install axios
const axios = require('axios');
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
Module Exporting and Importing in Node.js:
Exporting: Use module.exports
or exports
to make functions, objects, or primitive values available outside the module.
// math.js
function multiply(a, b) {
return a * b;
}
module.exports = { multiply };
Importing: Use require()
to import modules and access exported functionalities.
// app.js
const { multiply } = require('./math');
console.log(multiply(5, 4)); // Output: 20
Summary:
Node.js modules are essential for structuring and organizing code in applications. They facilitate code reuse, improve maintainability, and enable modular development. Whether using core modules, local modules, or third-party modules, understanding how to export and import functionalities is crucial for leveraging Node.js’s modular architecture effectively.
- 6 months ago
- Zaid Bin Khalid
- 475 Views
-
2