Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • 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
Open In App
Next Article:
Node Export Module
Next article icon

Node.js Custom Module

Last Updated : 03 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Node.js is a powerful, open-source JavaScript runtime engine built on Chrome’s V8 engine. It allows JavaScript to run outside the browser, making it ideal for building fast, scalable server-side applications like REST APIs and real-time apps.

One of Node.js key features is its modular architecture. While built-in modules handle core tasks, custom modules help organize code and add project-specific functionality. In this Article, you’ll learn how to create and export custom modules in Node.js.

What are Custom Modules?

Custom modules, as the name suggests, are user-defined modules that encapsulate specific functionality within your application. They enable you to organize your code, promote reusability, and enhance the maintainability of your project. Custom modules can range from simple utility functions to complex business logic or even third-party libraries. By creating and using custom modules, you ensure that your code is modular, which makes it easier to understand, test, and refactor.

Creating a Custom Module

To create a custom module, you need to define the functions, classes, or objects that the module should contain and then export them for use in other parts of your application. Let's break down the process into two parts: defining the module's contents and exporting them.

Defining Functions, Classes, or Objects in a Module:

Start by creating a new JavaScript file, which will act as your custom module. In this file, you can define functions, classes, or objects as you would in any JavaScript code.

For example, let's create a simple utility module named 'math-utils.js' with two functions for adding and multiplying numbers:

math-utils.js
// math-utils.js

function add(a, b) {
  return a + b;
}

function multiply(a, b) {
  return a * b;
}


Exporting Functions, Classes, or Objects using 'module.exports' or 'exports'

To make the functions, classes, or objects defined in your custom module accessible from other parts of your application, you need to export them using either 'module.exports' or 'exports'. Both methods achieve the same result, but their usage differs slightly.

Using 'module.exports':

math-utils.js
// math-utils.js
function add(a, b) {
  return a + b;
}
function multiply(a, b) {
  return a * b;
}
module.exports = {
  add,
  multiply
};


Using 'exports':

math-utils.js
// math-utils.js
function add(a, b) {
  return a + b;
}
function multiply(a, b) {
  return a * b;
}
exports.add = add;
exports.multiply = multiply;


In both cases, we've made the 'add' and 'multiply' functions available for importing into other files. You can now use the custom module in another part of your application like this:

filename: arthmetic.js

index.js
const mathUtils = require('./math-utils');
const sum = mathUtils.add(5, 3);
const product = mathUtils.multiply(5, 3);
console.log(`Sum: ${sum}, Product: ${product}`);


Output:

arthmetics
output


Using a Custom Module in Another File

Once you've created a custom module and exported its functionality, you can use it in other parts of your application. Let's explore how to load and access custom modules in another file.

Loading a Custom Module with 'require()'

To load a custom module, you can use the 'require()' function, just as you would for built-in core modules. Pass the relative file path of your custom module as an argument, and 'require()' will return an object containing the exported functionality.

Suppose we have a custom module named 'math-utils.js' with two exported functions, 'add()' and 'multiply()':

filename:math-utils.js

math-utils.js
// math-utils.js
function add(a, b) {
  return a + b;
}
function multiply(a, b) {
  return a * b;
}
module.exports = {
  add,
  multiply
};


To use this module in another file, say 'arthmetic.js', you can load it like this:

arthmetic.js
// arthmetic.js
const mathUtils = require('./math-utils');


Accessing Exported Functions, Classes, or Objects

Once you've loaded your custom module using 'require()', you can access its exported functions, classes, or objects through the returned object. Continuing with our 'math-utils.js' example, let's use the 'add()' and 'multiply()' functions in 'app.js':

arthmetic.js
// arthmetic.js
const mathUtils = require('./math-utils');
const sum = mathUtils.add(5, 3);
const product = mathUtils.multiply(5, 3);
console.log(`Sum: ${sum}, Product: ${product}`);


Output:

arthmetics
arthmetic


Organizing Code in Multiple Custom Modules

As your application grows, it's essential to keep your code organized and maintainable. One way to achieve this is by dividing your code into multiple custom modules, each responsible for a specific functionality or domain.

Consider an application that calculates various mathematical operations, like addition, multiplication, division, and subtraction. Instead of placing all functions in a single module, you can create separate custom modules for each operation:

  • 'addition.js': Contains the 'add()' function
  • 'multiplication.js': Contains the 'multiply()' function
  • 'division.js': Contains the 'divide()' function
  • 'subtraction.js': Contains the 'subtract()' function

Each module can be created and exported using the same pattern shown earlier.

For example, the 'addition.js' module would look like this:

addition.js
// addition.js
function add(a, b) {
  return a + b;
}
module.exports = add;

Now, in your 'arthmetic.js' file, you can load and use these custom modules like this:

arthmetic.js
// arthmetic.js
const add = require('./addition');
const multiply = require('./multiplication');
const divide = require('./division');
const subtract = require('./subtraction');
console.log(`Addition: ${add(5, 3)}`);
console.log(`Multiplication: ${multiply(5, 3)}`);
console.log(`Division: ${divide(6, 3)}`);
console.log(`Subtraction: ${subtract(5, 3)}`);

Output:

custommodule1
output


Conclusion

  • Custom modules help you organize and modularize your code effectively.
  • They make your code more maintainable and reusable.
  • You can define your own functions, classes, or objects within custom modules.
  • Use module.exports or exports to export functionality from a module.
  • They enable you to build a modular and extensible codebase.
  • Custom modules provide a solid foundation for developing scalable Node.js projects.

Next Article
Node Export Module

M

mahimabh9a46
Improve
Article Tags :
  • Node.js

Similar Reads

    Node.js VM Module
    The VM (Virtual Machine) module in Node.js lets you safely run JavaScript code in a separate, isolated environment. This feature is especially handy when you need to execute code without affecting the rest of your application, making it ideal for handling untrusted code or creating distinct executio
    4 min read
    Node.js Local Module
    A local module in Node.js refers to a custom module created in an application. Unlike the built in or third-party modules, local modules are specific to the project and are used to organize and reuse your code across different parts of your application.Local Module in Node.jsLocal modules in Node.js
    2 min read
    Node.js Local Module
    A local module in Node.js refers to a custom module created in an application. Unlike the built in or third-party modules, local modules are specific to the project and are used to organize and reuse your code across different parts of your application.Local Module in Node.jsLocal modules in Node.js
    2 min read
    Node Export Module
    In NodeJS, module.exports is used to share functions, objects, or values from one file to the other file so that other files can use them. This is an essential part of organizing and reusing code across different parts of your application, making it easier to manage and maintain.Here’s how exporting
    5 min read
    Node Export Module
    In NodeJS, module.exports is used to share functions, objects, or values from one file to the other file so that other files can use them. This is an essential part of organizing and reusing code across different parts of your application, making it easier to manage and maintain.Here’s how exporting
    5 min read
    Node.js require Module
    The primary object exported by the require() module is a function. When NodeJS invokes this require() function, it does so with a singular argument - the file path. This invocation triggers a sequence of five pivotal steps: Resolving and Loading: The process begins with the resolution and loading of
    3 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
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
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences