CommonJS
require / module.exports
Learn how Node.js organizes code into reusable modules using the CommonJS pattern: require() to import and module.exports to share.
What Is a Module?
A module is simply a single JavaScript file that contains related code: variables, functions, or classes. Instead of dumping everything into one giant file, you split your program into small, focused pieces.
Why CommonJS?
When Node.js was created in 2009, browsers had no built-in module system. CommonJS became the default standard for organizing server-side JavaScript. Every npm package you install uses CommonJS under the hood.
The Big Picture
The module.exports Rule
Every Node.js file automatically has a module object. The property module.exports is what gets returned when another file calls require() on it. You can export anything: a function, an object, a string, a number.
The require() Rule
require() is a built-in function that reads another file, executes it, and returns whatever that file set on module.exports. The argument is a file path (for your own files) or a package name (for npm modules).
exports vs module.exports
Node provides a shorthand variable called exports that initially points to the same object as module.exports. You can add properties to it, but never reassign it directly.
Exporting Multiple Values
To share several functions or variables, export an object with named properties. The importing file can then access each one individually.
How require() Works
Step-by-Step Checklist
Example 1: Single Export
Example 2: Object Export
Example 3: Class Export
Understanding Require Paths
Common Mistakes
CommonJS vs ES Modules
| CommonJS | ES Modules | |
|---|---|---|
| Import syntax | require() | import ... from |
| Export syntax | module.exports | export / export default |
| Loading | Synchronous | Asynchronous |
| Environment | Node.js (default) | Browsers + Node.js |
| File extension | .js (default) | .mjs or "type":"module" |
| Dynamic import | ✓ Built-in | ✓ import() |
Question 1 of 5
What does require('./utils') return?
Question 2 of 5
Which line correctly exports a function called calculate?
Question 3 of 5
If require('./math') is called three times in the same program, how many times does math.js actually execute?
Question 4 of 5
What happens if you write require('express') without a './' prefix?
Question 5 of 5
File: helpers.js
function double(n) { return n * 2; }
function triple(n) { return n * 3; }
module.exports = { double, triple };
File: main.js
const helpers = require('./helpers');
console.log(helpers.double(5));
What does main.js print to the console?