module export in node js
Module Export in Node.js
In Node.js, the module.exports
object is used to export functions, objects, or values from a module to make them accessible to other modules. Here are the steps involved in using module.exports
:
Define the module: Create a JavaScript file that contains the code you want to export. This file is known as a module.
Declare the exports: Inside the module, use the
module.exports
object to declare the functions, objects, or values that you want to make available to other modules. You can assign a function, an object, or a value directly tomodule.exports
.
Example: ```javascript // square.js module.exports.area = function (width) { return width * width; };
module.exports.perimeter = function (width) { return 4 * width; }; ```
In the above example, the area
and perimeter
functions are assigned to the module.exports
object.
- Import the module: In another module, use the
require()
function to import the module that exports the desired functions, objects, or values.
Example: ```javascript // main.js const square = require("./square");
console.log(square.area(5)); // Output: 25 console.log(square.perimeter(5)); // Output: 20 ```
In the above example, the require()
function is used to import the square.js
module. The exported functions area
and perimeter
can then be accessed using the square
object.
That's it! By following these steps, you can export and import functions, objects, or values between modules in Node.js using module.exports
and require()
.