Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
What are modules in Node JS ?
Next article icon

How To Create Modules in NodeJS?

Last Updated : 19 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Modules are the building blocks of NodeJS code. They help you break down your project into smaller, manageable pieces, each with its own job.

To create a module, just make a JavaScript file and export what you want to share. Other files can then import and use those exports, adding that functionality to their code.

Types of Modules

NodeJS has three types of modules:

  • Built-in Modules: Provided by NodeJS (e.g., fs, http, path).
  • User-defined Modules: Custom modules created by developers.
  • Third-party Modules: Modules installed via npm (e.g., express, lodash).

Steps to Create Modules in NodeJS

To create modules in NodeJS, write functions, objects, or classes in a separate file and use module.exports to export them. Import these modules in other files using the require() function for reuse.

Step 1: Creating a Module

To create a module, you simply need to write code in a separate file. You can then export specific variables, functions, or objects from that file to be used in other parts of your application.

Let’s start by creating a simple module that performs some basic mathematical operations.

File name: calc.js

javascript
exports.add = function (x, y) {     return x + y; }; exports.sub = function (x, y) {     return x - y; }; exports.mult = function (x, y) {     return x * y; }; exports.div = function (x, y) {     return x / y; }; 
  • The calc.js file defines four functions: add, sub, mult, and div.
  • These functions are exported as properties of the module.exports object, making them accessible to other files.

Step 2: Using a Module

Now that we’ve created a module, we can import it into another file and use the exported functions.

File name: App.js

javascript
const calculator = require('./calc'); let x = 50, y = 20; console.log("Addition of 50 and 20 is "     + calculator.add(x, y)); console.log("Subtraction of 50 and 20 is "     + calculator.sub(x, y)); console.log("Multiplication of 50 and 20 is "     + calculator.mult(x, y)); console.log("Division of 50 and 20 is "     + calculator.div(x, y)); 
  • The app.js file imports the calc.js module using require(‘./calc’).
  • It then uses the imported calculator object to perform arithmetic operations and logs the results.

Output

Create Module - output

Create Modules in NodeJS

Best Practices of Creating Modules in NodeJS

  • Use meaningful and descriptive names for your module files.
  • Keep your modules focused on a single responsibility (SRP).
  • Avoid global variables in your modules.


Next Article
What are modules in Node JS ?

A

ashitace696
Improve
Article Tags :
  • Node.js
  • Web Technologies
  • Node.js-Misc

Similar Reads

  • How to use EcmaScript Modules in Node.js ?
    Using ECMAScript Modules (ES Modules or ESM) in Node.js allows you to take advantage of modern JavaScript syntax for organizing and managing your code. ECMAScript Modules provide a more structured and standardized way to work with modules compared to CommonJS, which has been traditionally used in No
    2 min read
  • What are modules in Node JS ?
    In NodeJS, modules are encapsulated units of code that can be reused across different parts of an application. Modules help organize code into smaller, manageable pieces, promote code reusability, and facilitate better maintainability and scalability of NodeJS applications. Types of Modules:Core Mod
    2 min read
  • What are Modules in Node.js ?
    In Node.js Application, a Module can be considered as a block of code that provide a simple or complex functionality that can communicate with external application. Modules can be organized in a single file or a collection of multiple files/folders. Almost all programmers prefer modules because of t
    5 min read
  • How to Create a Dockerfile in Node.js ?
    A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. It is something like a shellscript that gathers multiple commands into a single document to fulfill a single task. Prerequisite: Before you can Dockerize any application, you ne
    4 min read
  • How to Run C Code in NodeJS?
    Developers can take advantage of Node.js's robust ecosystem and performance by running C code within the framework. Child processes, Node.js extensions, and the Foreign Function Interface (FFI) can all assist in this. There is flexibility to integrate C code based on particular requirements, as each
    3 min read
  • How to Install NodeJS on MacOS
    Node.js is a popular JavaScript runtime used for building server-side applications. It’s cross-platform and works seamlessly on macOS, Windows, and Linux systems. In this article, we'll guide you through the process of installing Node.js on your macOS system. What is Node.jsNode.js is an open-source
    7 min read
  • How to Change the Node.js Module Wrapper ?
    Changing the Node.js module wrapper involves customizing the way modules are wrapped by modifying the Module.wrap method. This allows for altering the function wrapper used in module loading. Module Wrapper FunctionUnder the hood, NodeJS does not run our code directly, it wraps the entire code insid
    2 min read
  • How to work Mongojs module in Node.js ?
    Mongojs module is a built-in module in node.js that facilitates the usage of MongoDB with Node.js. It offers almost all the functionality that is provided by the official API of MongoDB and is used extensively by developers across the globe.   Follow the steps mentioned below to install mongojs modu
    3 min read
  • How to remove all Global Modules in Node.js ?
    Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside of a browser. You need to remember that Node.js is not a framework and it’s not a programming language. Most of the people are confused and understand it’s a framework or a programming language. We
    2 min read
  • How to use External Modules and NPM in a project ?
    Need for External Modules: For a large JavaScript application, it becomes difficult and messy to write the whole code in just one JavaScript file. This is where CommonJS comes into the picture and this CommonJS format defines a module format that can be used up for breaking your JS application into
    3 min read
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