module.exports is a special object in Node.js used to export functions, objects, or variables defined in the module to other files (i.e., modules). In Node.js, each file is treated as a module, and by using module.exports, you can selectively export parts or all of the module's content. This allows other modules to import and use these functionalities via the require() function.
Example:
Suppose we have a file named math.js that defines some basic mathematical functions:
javascript// math.js function add(a, b) { return a + b; } function subtract(a, b) { return a - b; } // Export the add and subtract functions module.exports = { add, subtract };
In another file, we can use require to import the functions from math.js:
javascript// app.js const math = require('./math'); const result1 = math.add(1, 2); const result2 = math.subtract(3, 1); console.log(result1); // Output: 3 console.log(result2); // Output: 2
In this example, math.js exports the add and subtract functions via module.exports, while app.js imports these functions using require('./math') and uses them.
Summary:
By using module.exports, Node.js supports modular programming, which enhances code reusability, maintainability, and testability. It enables developers to create modular components with distinct functionalities and import and use them as needed.