Modules are a way to organize code into reusable pieces.
Each file in Node.js is considered a module, and you can export functions, objects, or values from one module to be used in another module using the module.exports
object. Conversely, you can import these exported values into another module using the require()
function
//Creating a Module
// Exporting functions
exports.add = function(a, b) {
return a + b;
};
exports.subtract = function(a, b) {
return a - b;
};
// app.js
// Importing the math module
const math = require('./math');
// Using the exported functions
console.log(math.add(5, 3)); // Output: 8
console.log(math.subtract(5, 3)); // Output: 2
© www.thecoderjob.com. All Rights Reserved. Designed by HTML Codex