01 / 21

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.

JavaScript

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.

Self-Contained
Each file has its own scope: variables inside one module don't leak into another.
Reusable
Write a function once, then use it in many files by importing the module.
Maintainable
Small files are easier to read, test, and debug than monolithic scripts.

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

math.js function add(a, b) { return a + b; } module.exports = add; EXPORTS require() app.js const add = require('./math'); console.log(add(2, 3)); // 5 IMPORTS

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.

// greet.js function greet(name) { return `Hello, ${name}!`; } module.exports = greet;

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).

// app.js const greet = require('./greet'); console.log(greet('Alice')); // Hello, Alice!

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.

✓ Works
exports.add = function(a,b) { return a+b; };
✕ Broken
exports = function(a,b) { return a+b; };

Exporting Multiple Values

To share several functions or variables, export an object with named properties. The importing file can then access each one individually.

// mathUtils.js function add(a, b) { return a + b; } function multiply(a, b) { return a * b; } module.exports = { add, multiply };
// app.js const { add, multiply } = require('./mathUtils'); console.log(add(2, 3)); // 5 console.log(multiply(4, 5)); // 20

How require() Works

1
Resolve the path. Node finds the file using the string you passed: a relative path ('./math') or an npm package name ('lodash').
2
Read and execute. Node reads the file's source code and runs it inside a function wrapper that provides module, exports, require, __dirname, and __filename.
3
Cache the result. The value of module.exports is cached. Future calls to require() return the cached copy: the file runs only once.
4
Return module.exports. The require() call evaluates to whatever module.exports was set to in that file.

Step-by-Step Checklist

1
Create a new file for each concern (e.g., database.js, helpers.js).
2
Write your code inside that file: functions, constants, or a class.
3
Assign to module.exports at the bottom. Export one value or an object with multiple named properties.
4
In the consuming file, call require('./filename') and store the result in a const.
5
Use destructuring if the export is an object: const { fn1, fn2 } = require('./file');

Example 1: Single Export

logger.js function log (msg) { console.log(msg); } module.exports = log; index.js const log = require ('./logger') log ('Server started'); // Server started

Example 2: Object Export

// config.js const PORT = 3000; const DB_URL = 'mongodb://localhost/myapp'; module.exports = { PORT, DB_URL };
// server.js const { PORT, DB_URL } = require('./config'); console.log(`Listening on port ${PORT}`); console.log(`DB: ${DB_URL}`);

Example 3: Class Export

// User.js class User { constructor(name, age) { this.name = name; this.age = age; } greet() { return `Hi, I'm ${this.name}`; } } module.exports = User;
// app.js const User = require('./User'); const alice = new User('Alice', 17); console.log(alice.greet()); // Hi, I'm Alice

Understanding Require Paths

'./file'
Relative path: looks for file.js in the same directory as the current file.
'../file'
Goes up one directory, then finds file.js. Use for sibling folders.
'lodash'
No dot prefix: Node searches in node_modules for an installed npm package.

Common Mistakes

✕ Missing './' Prefix
Writing require('math') instead of require('./math') makes Node look in node_modules, not your folder.
✕ Reassigning exports
Writing exports = myFunc breaks the reference. Always use module.exports = myFunc instead.
✕ Forgetting to Export
Defining a function but never setting module.exports means require() returns an empty object {}.

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

What does main.js print to the console?