Skip to content
- Tutorials
- Python Tutorial
- Taking Input in Python
- Python Operators
- Python Data Types
- Python Loops and Control Flow
- Python Functions
- Python OOPS Concept
- Python Data Structures
- Python Exception Handling
- Python File Handling
- Python Exercises
- Java
- Java Programming Language
- Java Collections
- Java 8 Tutorial
- Java Programs
- Java Interview Questions
- Java Exercises
- Java Quiz
- Java Projects
- Advance Java
- Programming Languages
- System Design
- Interview Corner
- Computer Science Subjects
- DevOps
- Linux
- Software Testing
- Databases
- Android
- Excel
- Mathematics
- Python Tutorial
- DSA
- Data Structures
- Algorithms
- Analysis of Algorithms
- Searching Algorithms
- Sorting Algorithms
- Greedy Algorithms
- Dynamic Programming
- Graph Algorithms
- Pattern Searching
- Recursion
- Backtracking
- Divide and Conquer
- Mathematical Algorithms
- Geometric Algorithms
- Bitwise Algorithms
- Randomized Algorithms
- Branch and Bound
- Algorithms Tutorial
- DSA Tutorial
- Practice
- All DSA Problems
- Problem of the Day
- Company Wise Coding Practice
- GfG SDE Sheet
- Practice Problems Difficulty Wise
- Language Wise Coding Practice
- Curated DSA Lists
- Competitive Programming
- Company Wise SDE Sheets
- DSA Cheat Sheets
- Top Interview Questions
- Puzzles
- Data Science
- Web Tech
- Courses
-
- Full Stack Course
- NodeJS Tutorial
- NodeJS Exercises
- NodeJS Assert
- NodeJS Buffer
- NodeJS Console
- NodeJS Crypto
- NodeJS DNS
- NodeJS File System
- NodeJS Globals
- NodeJS HTTP
- NodeJS HTTP2
- NodeJS OS
- NodeJS Path
- NodeJS Process
- NodeJS Query String
- NodeJS Stream
- NodeJS String Decoder
- NodeJS Timers
- NodeJS URL
- NodeJS Interview Questions
- NodeJS Questions
- Web Technology
Last Updated : 31 Mar, 2023
Summarize
Comments
Improve
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.
Purpose:
- 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 the 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.
node -v
Step 1: Create a separate folder and then navigate to that folder by terminal or command prompt.
Step 2:Run the npm init -y command in the terminal or command prompt to create a 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 look like this:
Step 4:Add the following code to the module.js file
Javascript
// Module.js file
See AlsoCan I export more than one object using module.exports?Different Types of Export in ReactThe Difference between ‘module.export’ and ‘export default’Export Risk Management | How to Mitigate Risk | Allianz Trade USfunction
addTwoNumbers(a, b) {
return
a + b;
}
function
multiplyTwoNumbers(a, b) {
return
a * b;
}
const exportedObject = { addTwoNumbers, multiplyTwoNumbers };
// module.exports can be used to export
// single function but we are exporting
// object having two functions
module.exports = exportedObject;
Step 5:Add the following code to app.js file
Javascript
// app.js file
const obj = require(
"./module"
);
// Getting object exported from module.js
console.log(obj);
// Printing object exported from
// module.js that contains
// references of two functions
const add = obj.addTwoNumbers;
// Reference to addTwoNumbers() function
console.log(add(3, 4));
const multiply = obj.multiplyTwoNumbers;
// Reference to multiplyTwoNumbers() function
console.log(multiply(3, 4));
Step to run the application: Run the following command in your terminal inside your root path of the project (eg:module_exports_tut) folder.
node app.js
Output:
For more information about the module.exports visit https://www.geeksforgeeks.org/node-js-export-module/
Please Login to comment...
Similar Reads
Difference between module.exports and exports in Node.js
The module is a plain JavaScript Object representing the current module. It is local to each module and also it is private. It has exports property which is a plain JavaScript variable, set to module.exports. At the end of the file, Node.js return module.exports to the required function. About module.exports: When we want to export a single class/v
2 min read
How to write code using module.exports in Node.js ?
module is a discrete program, contained in a single file in Node.js. They are tied to files with one module per file. module.exports is an object that the current module returns when it is "required" in another program or module. We are going to see a simple code like the calculator to learn how to use module.exports in Node.js. I will walk you thr
3 min read
What is the Purpose of Exports Array in NgModule?
NgModule is a class marked by the @NgModule decorator. It identifies the module's own components, directives, and pipes, making some of them public, through the exports property, so that external components can use them. The @NgModule decorator takes a metadata object as an argument. This object configures various aspects of the module, such as dec
3 min read
Error: Warning: Accessing non-existent property 'findOne' of module exports inside circular dependency
It looks like you're trying to use a method called findOne but it doesn't exist. This error message suggests that there is a circular dependency in your code, which means that two or more modules are trying to import each other. This can cause problems because the modules can't be resolved properly. This error indicates that there is a problem with
3 min read
How to Import all Exports of a File as an Object in Node.js ?
In Node.js, you can import all exports of a file as an object using the ES Modules syntax (import) or the CommonJS syntax (require). This approach is useful when you have multiple exports from a module and want to access them conveniently through a single object interface. Below are the approaches to Import all Exports of a File as an Object in Nod
4 min read
Difference Between Default & Named Exports in JavaScript
In JavaScript module facilitates the "export", of variables, functions, or classes from one module to another. This system primarily offers two approaches for exporting, Named Exports and Default Exports. Named exports to allow multiple values to be exported from a module with specific names, while default exports are used for single value or modul
4 min read
How to export promises from one module to another module node.js ?
JavaScript is an asynchronous single-threaded programming language. Asynchronous means multiple processes are handled at the same time. Callback functions vary for the asynchronous nature of the JavaScript language. A callback is a function that is called when a task is completed, thus helps in preventing any kind of blocking and a callback functio
1 min read
What is the purpose of the path module in NodeJS?
The path module in NodeJS provides utilities for working with file and directory paths. It offers methods to manipulate file paths, resolve relative paths, extract file extensions, and more. Here's why the path module is essential in NodeJS development: Path Manipulation: Easily manipulate file paths using methods like path.join() to concatenate pa
1 min read
What are the differences between HTTP module and Express.js module ?
HTTP and Express both are used in NodeJS for development. In this article, we'll go through HTTP and express modules separately HTTP: It is an in-build module which is pre-installed along with NodeJS. It is used to create server and set up connections. Using this connection, data sending and receiving can be done as long as connections use a hypert
2 min read
How to allow classes defined in a module that can be accessible outside of the module ?
The TypeScript scripts written by default are in the global scope which means that all the functions, methods, variables, etc. in one file are accessible in all other TypeScript files. This can lead to conflicts in variables, functions as programmers can edit the function/variable name or value without any realization. Therefore, the concept of mod
3 min read
How do you import a module into another module Angular?
Angular applications are modular by design, allowing you to break down complex functionalities into smaller, manageable pieces called modules. One common task in Angular development is importing modules into other modules to make their components, directives, pipes, and services available throughout the application. This article explores the proces
4 min read
How to Allow Classes Defined in a Module to be Accessible Outside of a Module ?
In Node.js, the modular system allows you to organize your code into separate files, known as modules. This not only helps in managing and maintaining your code but also makes it reusable. One of the key features of modules is the ability to export classes, functions, or variables so they can be accessed from other files. This article will guide yo
5 min read
What is the purpose of process object in Node.js ?
A process object is a global object available in the Node.js environment. It is globally available. We do not have to use the require() to import the module of the process object. The "process" object use to get current Node.js process details & also give control over that process. Properties of the process object: Some of the commonly used Nod
2 min read
What is the purpose of the Buffer class in Node ?
In Node, the Buffer class plays a crucial role in handling binary data, allowing developers to work with raw binary data directly. The Buffer class provides a way to create, manipulate, and convert binary data efficiently, making it essential for various tasks such as file I/O, network communication, cryptography, and data manipulation. Let's explo
2 min read
What is the purpose of the process object in Node JS ?
In NodeJS, the process object is a global object that provides access to information and control over the current NodeJS process. It offers various properties and methods to interact with the underlying operating system environment and manage the NodeJS process effectively. Let's explore the primary purposes of the process object in NodeJS. Accessi
2 min read
What is the Purpose of __filename Variable in Node.js ?
In Node.js, there are several global variables that are available in all modules. One such variable is __filename. This article delves into the purpose, usage, and practical applications of the __filename variable in Node.js. What is __filename?The __filename variable is a built-in global variable in Node.js that provides the absolute path of the f
3 min read
Node JS | Password Hashing with Crypto module
In real-life applications with User authentication functionality, storing the user passwords as the original string in the database is not practical. Still, it is good practice to hash the password and then store them in the database. Crypto module for Node JS helps developers to hash user passwords. Examples: Original Password : portalforgeeks Has
5 min read
Node.js HTTP Module Complete Reference
To make HTTP requests in Node.js, there is a built-in module HTTP in Node.js to transfer data over the HTTP. To use the HTTP server in the node, we need to require the HTTP module. The HTTP module creates an HTTP server that listens to server ports and gives a response back to the client. Example: C/C++ Code // Node.js program to demonstrate the //
4 min read
Password Hashing with MD5 module in Node.js
MD5 module in node.js uses a message-digest algorithm and it is a widely used hash function producing a 128-bit hash value. Password hashing is an important concept because, in the database, the actual password should not be stored as its a bad practice and also make the system less secure, so the password is stored in hashed form into the database
2 min read
How to Run Synchronous Queries using sync-sql Module in Node.js ?
The sync-sql module is designed to make synchronous queries to the database. Since normal SQL queries are asynchronous in node.js but if you want to run it synchronously, then it is possible using this module. In synchronized SQL, the result set is returned when the query is executed. Note: Do not use this module in production mode as node.js is de
2 min read
Node.js Request Module
The request module is used to make HTTP calls. It is the simplest way of making HTTP calls in node.js using this request module. It follows redirects by default. Note: As of Feb 11th, 2020, the request is fully deprecated. Feature of Request module: It is easy to get started and easy to use.It is a widely used and popular module for making HTTP cal
2 min read
How to Validate Data using validator Module in Node.js ?
The Validator module is popular for validation. Validation is necessary to check whether the data is correct or not, so this module is easy to use and validates data quickly and easily. Feature of validator module: It is easy to get started and easy to use.It is a widely used and popular module for validation.Simple functions for validation like is
2 min read
How to Upload File using formidable module in Node.js ?
A formidable module is used for parsing form data, especially file uploads. It is easy to use and integrate into your project for handling incoming form data and file uploads. Installation of the formidable module: You can visit the link Install formidable module. You can install this package by using this command. npm install formidable After inst
2 min read
Node.js Yargs Module
Yargs module is used for creating your own command-line commands in node.js and helps in generating an elegant user interface. This module makes command-line arguments flexible and easy to use. Installation of yargs module: You can visit the link Install yargs module. You can install this package by using this command. npm install yargs After insta
2 min read
Session Management using express-session Module in Node.js
Session management can be done in node.js by using the express-session module. It helps in saving the data in the key-value form. In this module, the session data is not saved in the cookie itself, just the session ID. Installation of express-session module: You can visit the link Install express-session module. You can install this package by usin
2 min read
How to Validate Data using express-validator Module in Node.js ?
Validation in node.js can be easily done by using the express-validator module. This module is popular for data validation. There are other modules available in market like hapi/joi, etc but express-validator is widely used and popular among them.Steps to install express-validator module: You can install this package by using this command. npm inst
3 min read
How to Generate fake data using Faker module in Node.js ?
Faker module is used to generate fake data, not only fake data, infect well organized fake data. Faker module is a widely used NPM module that can generate fake names, addresses, product names, prices with all these you can also generate fake IP addresses, images, and much more using this faker package.Command to install faker module: npm install f
2 min read
Node.js Redis Module
Redis is an Open Source store for storing data structures. It is used in multiple ways. It is used as a database, cache, and message broker. It can store data structures such as strings, hashes, sets, sorted sets, bitmaps, indexes, and streams. Redis is very useful for Node.js developers as it reduces the cache size which makes the application more
4 min read
How to Display Flash Messages using connect-flash Module in Node.js ?
Connect-flash module for Node.js allows the developers to send a message whenever a user is redirecting to a specified web-page. For example, whenever, a user successfully logged in to his/her account, a message is flashed(displayed) indicating his/her success in the authentication.Prerequisites Before starting with the application, you must have t
3 min read
Node.js Timers module
The Timers module in Node.js contains various functions that allow us to execute a block of code or a function after a set period of time. The Timers module is global, we do not need to use require() to import it. The timers module has the following functions: Scheduling Timers: It is used to call a function after a set period of time. setImmediate
3 min read
Article Tags :
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `
${comment_text}
`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `
${suggest_val}
`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `
Thank You!
Your suggestions are valuable to us.
You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.
`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });