What if you could organize your Node.js code like neat building blocks instead of a tangled mess?
Why CommonJS require and module.exports in Node.js? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine writing a Node.js app where you copy and paste all your functions into one big file. Every time you want to reuse code, you have to scroll through hundreds of lines or copy code manually.
This manual approach is messy and confusing. It's easy to make mistakes, like overwriting code or forgetting to update all copies. It also makes your app slow to understand and hard to fix.
CommonJS modules let you split your code into separate files and share functions easily. Using require and module.exports, you can load and use code from other files cleanly and safely.
function greet() { console.log('Hello!'); } // repeated in many filesconst greet = require('./greet'); greet();This makes your code organized, reusable, and easier to maintain as your app grows.
Think of building a website where you keep your database code, user login, and page rendering in separate files. CommonJS modules help you connect these parts without mixing everything together.
Manual code copying is error-prone and hard to manage.
CommonJS modules let you share code between files easily.
This leads to cleaner, more maintainable Node.js apps.
Practice
module.exports do in a Node.js file?Solution
Step 1: Understand module.exports role
module.exports sets the object or value that other files receive when they use require() on this module.Step 2: Differentiate from require()
require() is used to import, while module.exports is used to export code from a module.Final Answer:
It defines what the module shares when required by another file. -> Option DQuick Check:
module.exports = export code [OK]
- Confusing require() with module.exports
- Thinking module.exports runs code
- Assuming module.exports deletes modules
utils.js using CommonJS?Solution
Step 1: Identify local module import syntax
Local files require a relative path starting with './' or '../' in require().Step 2: Check each option
const utils = require('./utils'); uses require('./utils'), which correctly imports the local utils.js file. const utils = require('utils'); misses './', so it looks for a package. import utils from './utils'; uses ES module syntax, not CommonJS. const utils = import('./utils'); uses dynamic import, not CommonJS.Final Answer:
const utils = require('./utils'); -> Option AQuick Check:
Local modules need './' in require() [OK]
- Omitting './' for local modules
- Using ES module import syntax in CommonJS
- Using import() instead of require()
node app.js runs?// math.js
module.exports.add = (a, b) => a + b;
module.exports.sub = (a, b) => a - b;
// app.js
const math = require('./math');
console.log(math.add(5, 3));
console.log(math.sub(5, 3));Solution
Step 1: Understand exports in math.js
math.js exports two functions: add and sub, which add and subtract two numbers.Step 2: Trace app.js calls
app.js requires math.js and calls math.add(5, 3) which returns 8, and math.sub(5, 3) which returns 2.Final Answer:
8 and 2 -> Option BQuick Check:
5+3=8 and 5-3=2 [OK]
- Expecting undefined because of wrong export syntax
- Confusing module.exports with exports shorthand
- Forgetting to require the module
// greet.js
exports = function() { return 'Hello'; };
// app.js
const greet = require('./greet');
console.log(greet());Solution
Step 1: Analyze exports assignment in greet.js
Assigning directly to exports replaces the local exports variable but does not change module.exports, so require() gets an empty object.Step 2: Understand require() result in app.js
Since module.exports was not changed, greet is an empty object, not a function, so calling greet() causes an error.Final Answer:
greet is not a function because exports was overwritten incorrectly. -> Option CQuick Check:
Overwrite exports breaks module.exports [OK]
- Assigning function directly to exports instead of module.exports
- Expecting exports and module.exports to be the same after reassignment
- Ignoring that require() returns module.exports
class User {
constructor(name) {
this.name = name;
}
}
// What should you write here?Solution
Step 1: Understand exporting a single value
To export a single class so require() returns it directly, assign it to module.exports.Step 2: Compare options
module.exports = User; assigns User directly to module.exports, so require('./module') returns the class. module.exports.User = User; and exports.User = User; export an object with User property, so require() returns an object, not the class itself. export default User; uses ES module syntax, invalid in CommonJS.Final Answer:
module.exports = User; -> Option AQuick Check:
Single export = module.exports = value [OK]
- Using exports.User instead of module.exports for single export
- Mixing ES module syntax with CommonJS
- Expecting require() to return class when exporting as property
