Node.js Modules
# 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;
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.");
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 };
javascript id="ch4-code-2" // app.js const greetings = require('./greetings');
console.log(greetings.sayHello("Alice")); console.log(greetings.sayGoodbye("Bob"));
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!
javascript id="ch4-code-4" // math.js exports.add = (a, b) => a + b; exports.subtract = (a, b) => a - b;
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 };
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. What is a module in Node.js?
-
2.
What is the difference between require()
andmodule.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.
-
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.