1. Writing and Using Custom Modules
In Node.js, modules are building blocks that help organize code into reusable components. While Node.js provides many built-in modules like fs, path, and http, developers can also create custom modules to encapsulate functionality and enhance code maintainability. Understanding how to write and use custom modules is crucial for creating scalable and modular applications.
2. What Are Custom Modules?
A custom module in Node.js is simply a file containing JavaScript code that can be exported and used in other files. Custom modules allow you to:
3. Creating a Custom Module
To create a custom module, follow these steps:
1. Create a New File:
Create a new JavaScript file, for example, mathOperations.js.
2. Write the Module Code:
Define the functions, variables, or objects you want to export.
// mathOperations.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
// Export the functions
module.exports = {
add,
subtract
};
In this example, the add and subtract functions are exported as part of an object.
4. Using a Custom Module
To use the custom module in another file, follow these steps:
1. Import the Module:
Use require() to load the custom module.
// app.js
const mathOperations = require('./mathOperations');
const sum = mathOperations.add(5, 3);
const difference = mathOperations.subtract(10, 4);
console.log(`Sum: ${sum}`); // Output: Sum: 8
console.log(`Difference: ${difference}`); // Output: Difference: 6
2. Run the Code:
Execute the file using Node.js.
node app.js
You will see the output in the console displaying the results of the add and subtract functions.
5. Exporting Individual Functions
Instead of exporting an object, you can export individual functions directly:
// greet.js
module.exports = function greet(name) {
return `Hello, ${name}!`;
};
Then import it like this:
// app.js
const greet = require('./greet');
console.log(greet('Alice')); // Output: Hello, Alice!
6. Using the exports Object
You can also use exports as an alias for module.exports:
// logger.js
exports.logInfo = function (message) {
console.log(`INFO: ${message}`);
};
exports.logError = function (error) {
console.error(`ERROR: ${error}`);
};
To use it:
// app.js
const logger = require('./logger');
logger.logInfo('Server started successfully.');
logger.logError('Failed to connect to the database.');
7. Benefits of Custom Modules
8. Custom Modules with Classes
Custom modules can also export classes, allowing for more structured and object-oriented code:
// calculator.js
class Calculator {
add(a, b) {
return a + b;
}
multiply(a, b) {
return a * b;
}
}
module.exports = Calculator;
Usage:
// app.js
const Calculator = require('./calculator');
const calc = new Calculator();
console.log(calc.add(4, 2)); // Output: 6
console.log(calc.multiply(3, 5)); // Output: 15
9. Working with Multiple Exports
Custom modules can export multiple items, such as functions, objects, or constants:
// utilities.js
const PI = 3.14;
function areaOfCircle(radius) {
return PI * radius * radius;
}
function circumferenceOfCircle(radius) {
return 2 * PI * radius;
}
module.exports = {
areaOfCircle,
circumferenceOfCircle,
PI
};
To use these exports:
// app.js
const { areaOfCircle, circumferenceOfCircle, PI } = require('./utilities');
console.log(`Area: ${areaOfCircle(5)}`); // Output: Area: 78.5
console.log(`Circumference: ${circumferenceOfCircle(5)}`); // Output: Circumference: 31.4
console.log(`Value of PI: ${PI}`); // Output: Value of PI: 3.14