Creating a Module in Node.js
Overview
In Node.js, a module is a reusable block of code that encapsulates related functionality. You can create your own modules to organize your code better and promote code reusability.
Creating a Simple Module
To create a module, follow these steps:
- Create a new JavaScript file for your module.
- Export the functions or variables you want to expose.
- Import the module in your main application file.
Example Module
Here's an example of creating a simple module called math.js
that exports addition and subtraction functions:
// math.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
// Export functions
module.exports = { add, subtract };
Using the Module
Now, you can import and use the math.js
module in another file:
// app.js
const math = require('./math');
console.log(math.add(5, 3)); // Output: 8
console.log(math.subtract(5, 3)); // Output: 2