What is the purpose of module.exports in node.js ?
The module.exports is actually a property of the module object in node.js. module. Exports is the object that is returned to the require() call. By module.exports, we can export functions, objects, and their references from one file and can use them in other files by importing them by require() method.
- The main purpose of module.exports is to achieve modular programming. Modular programming refers to separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality. By not using module.exports it becomes difficult to write a large program without modular/reusable code.
- Using module.exports we can separate business logic from other modules. In other terms, we can achieve abstraction using it.
- By Using it becomes easy to maintain and manage the code base in different modules.
- Enforces separation of concerns. Having our code split up into multiple files allows us to have appropriate file names for every file. This way we can easily identify what every module does and where to find it (assuming we made a logical directory structure which is still your responsibility.
Example: How to use module.exports in node.js. To start with the following example it is necessary to have node.js installed on your pc.
For verifying type the following command in the terminal. It will show the installed version of Node.Js on your pc.
Step 1: Create a separate folder and then navigate to that folder by terminal or command prompt.
Step 2: Run npm init -y command in terminal or command prompt to create package.json file
Step 3: Now create two files at the root of your project structure named module.js and app.js respectively.
Project structure: It will looks like this:
Step 4: Add following code in module.js file
Step 5: Add the following code in app.js file
Step to run the application: Run following command in your terminal inside your root path of project (eg:module_exports_tut) folder.
For more information about module.exports visit https://www.geeksforgeeks.org/node-js-export-module/