Skip to main content
Node.js Basics
CHAPTER 04 Beginner

Node.js Modules

Updated: May 13, 2026
15 min read

# Node.js Modules

Welcome to Chapter 4! As your application grows, writing all your code in a single file like index.js becomes impossible to manage. Imagine trying to read a 10,000-line file to find one bug! To solve this, Node.js uses a Module System. In this chapter, we will learn how to split our code into separate, reusable files (modules) and connect them together.

---

1. Introduction

A module is simply a JavaScript file containing code that is encapsulated (hidden) from the rest of your application unless you explicitly share it.

Think of building a car: you don't build the entire car from a single massive piece of metal. You build the engine, the doors, and the wheels separately (as modules), and then assemble them together. Node.js works exactly the same way.

---

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Understand the CommonJS module system.
  • Export variables and functions using module.exports.
  • Import custom modules using the require() function.
  • Differentiate between Core Modules and Local Modules.
  • Create and organize a multi-file Node.js application.

---

3. Beginner-Friendly Explanations

What is CommonJS?

Node.js historically uses a module system called CommonJS. In CommonJS, every file is treated as a separate module. By default, anything you write inside a file stays inside that file. To share it with other files, you have to "export" it.

module.exports

This is how you share your code. Think of module.exports as a shipping box. You put the functions, variables, or objects you want to share inside this box. When another file wants to use your code, they open this box.

require()

This is how you import code. It is a built-in Node.js function used to load modules. You provide the path to the file you want to load, and require() returns whatever was put in the module.exports box of that file.

---

4. Syntax Explanation

Let's see the basic syntax of exporting and importing.

Exporting (in logger.js): ``javascript id="ch4-syntax-1" function logMessage(msg) { console.log([INFO]: ${msg}`); }

// Put the function into the export box module.exports = logMessage;

1
**Importing (in `app.js`):**

javascript id="ch4-syntax-2" // Use require() and provide the relative path // Note: './' means "in the same folder" const logger = require('./logger');

logger("Server has started.");

12345678910111213141516171819202122
**Output Explanation:**
When you run `node app.js`, Node looks for `logger.js` in the same directory, grabs the `logMessage` function that was exported, assigns it to the `logger` constant, and executes it.

---

## 5. Real-world Examples

**Why modularize?**
If you are building an e-commerce backend, you wouldn't put database logic, payment processing, and user authentication in the same file. 
You would create:
- `auth.js` (Handles login/registration)
- `payments.js` (Talks to Stripe or PayPal)
- `database.js` (Saves data)
- `server.js` (The main file that `require()`s the others to start the app)

---

## 6. Multiple Code Examples

### Example 1: Exporting an Object (Multiple things)
Usually, you want to export more than one function from a file.

javascript id="ch4-code-1" // greetings.js const sayHello = (name) => Hello, ${name}!; const sayGoodbye = (name) => Goodbye, ${name}!;

// Export an object containing both functions module.exports = { sayHello: sayHello, sayGoodbye: sayGoodbye };

1

javascript id="ch4-code-2" // app.js const greetings = require('./greetings');

console.log(greetings.sayHello("Alice")); console.log(greetings.sayGoodbye("Bob"));

123
### Example 2: Object Destructuring on Import
You can use modern JavaScript destructuring to only import what you need.

javascript id="ch4-code-3" // app.js // Only grabbing sayHello from the module const { sayHello } = require('./greetings');

console.log(sayHello("Charlie")); // sayGoodbye("Charlie") would throw an error here because it wasn't imported!

123
### Example 3: Exporting directly
You can attach properties directly to `exports`.

javascript id="ch4-code-4" // math.js exports.add = (a, b) => a + b; exports.subtract = (a, b) => a - b;

1234567891011121314151617181920212223242526272829303132333435363738394041
---

## 7. Output Explanations

When using `require()`, Node.js actually wraps your module's code in a hidden function behind the scenes. This is why variables declared in one file don't accidentally overwrite variables with the same name in another file. They are scoped locally to their specific file.

---

## 8. Common Mistakes

1. **Forgetting the `./` in require:** If you write `require('logger')` instead of `require('./logger')`, Node.js will think you are looking for a built-in Core Module or an NPM package, and it will throw an error saying `Cannot find module 'logger'`.
2. **Overwriting module.exports:** 
   ```javascript
   module.exports.add = add;
   module.exports = subtract; // This completely wipes out 'add'!
   ```
   If you need to export multiple things, use an object!
3. **Circular Dependencies:** When File A requires File B, and File B requires File A. This causes an infinite loop of importing and will break your app.

---

## 9. Best Practices

- **One concept per file:** A file named `userController.js` should only handle user-related logic. Don't put product or payment logic in it.
- **Use Destructuring:** When importing, use object destructuring (`const { fn1, fn2 } = require('./module')`). It makes it obvious exactly which functions your file is using.
- **Omit the .js extension:** When requiring files, you don't need to write `require('./math.js')`. Node automatically assumes it's a `.js` file, so `require('./math')` is cleaner.

---

## 10. Exercises

1. Create a module named `stringUtils.js`. Write two functions: `capitalize(word)` and `reverse(word)`. Export them both.
2. Create an `app.js` file, import `stringUtils.js`, and log the capitalized and reversed versions of the word "node".

---

## 11. Mini Project: Math utility module

**Objective:** Build a simple modular application that performs math operations.

**Step 1: Create the module (`mathUtil.js`)**

javascript id="ch4-mini-project-1" // mathUtil.js

const add = (a, b) => a + b; const subtract = (a, b) => a - b; const multiply = (a, b) => a * b; const divide = (a, b) => { if (b === 0) return "Error: Cannot divide by zero"; return a / b; };

// Exporting all functions as an object module.exports = { add, subtract, multiply, divide };

1
**Step 2: Create the main file (`calculator.js`)**

javascript id="ch4-mini-project-2" // calculator.js const math = require('./mathUtil');

const num1 = 10; const num2 = 5;

console.log("--- Math Operations ---"); console.log(Addition: ${num1} + ${num2} = ${math.add(num1, num2)}); console.log(Subtraction: ${num1} - ${num2} = ${math.subtract(num1, num2)}); console.log(Multiplication: ${num1} * ${num2} = ${math.multiply(num1, num2)}); console.log(Division: ${num1} / ${num2} = ${math.divide(num1, num2)}); ``

Run it: node calculator.js

---

12. Coding Challenges

Challenge 1: Expand the Math utility module to include a function calculateSquare(number). Update the main file to test it.

Challenge 2: Create a config.js file that exports an object containing database credentials (username, password, port). Import this into app.js and print them cleanly using console.table().

---

13. MCQs with Answers

Q1: In Node.js, how do you make a function accessible to other files? A) window.export = myFunction B) module.exports = myFunction C) import.myFunction D) require = myFunction Answer: B

Q2: Which built-in function is used to include a local module? A) import() B) include() C) require() D) fetch() Answer: C

Q3: Why must you use ./ or ../ when requiring a custom file? A) Because JavaScript requires absolute URLs. B) To tell Node.js it is a local file, not a built-in Node package. C) For security reasons. D) It is an optional styling choice. Answer: B

Q4: Node's default module system is known as: A) ES Modules (ESM) B) Asynchronous Module Definition (AMD) C) CommonJS D) RequireJS Answer: C

---

14. Interview Questions

  1. 1. What is a module in Node.js?
*Answer:* A module is a single or multiple JavaScript files containing reusable, encapsulated code. It prevents variable pollution in the global scope.
  1. 2. What is the difference between require() and module.exports?
*Answer:* module.exports is used to expose functions/objects from a file, making them public. require() is used to consume/import those exposed functions into another file.
  1. 3. If two different files require() the same module, does Node.js load it twice?
*Answer:* No. Node.js caches modules after the first time they are loaded. Subsequent require() calls return the cached version, saving memory and processing time.

---

15. FAQs

Q: I've seen import ... from ... in React. Why are we using require()? A: import/export is the modern ES6 Module (ESM) syntax. While Node.js now supports ESM, CommonJS (require) was the standard for over a decade and is still extremely common in legacy and current backend codebases. It is vital to learn CommonJS first.

Q: Can I require JSON files? A: Yes! You can require('./data.json') and Node.js will automatically parse the JSON file into a JavaScript object for you.

---

16. Summary

  • Code organization is critical in backend development.
  • Modules help split code into reusable files.
  • Use module.exports to expose your code to the rest of your app.
  • Use require('./filename') to pull that code into the current file.
  • Always use relative paths (./ or ../`) when importing your own files to differentiate them from NPM packages.

---

17. Next Chapter Recommendation

Now that you know how to link different files together, it's time to interact with the computer's hard drive! In Chapter 5: Node.js File System (fs Module), we will explore Node's built-in tools for creating, reading, updating, and deleting actual files on your computer.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·