CommonJS Modules
๐ Covered in this chapter:
require() ยท module.exports ยท Module Scope ยท Module Caching ยท Circular Dependencies
Understand Node.js's original module system: require(), module.exports, and how modules are scoped and cached.
1CommonJS Modules โ What You'll Learn
Understand Node.js's original module system: require(), module.exports, and how modules are scoped and cached.
Here's everything this chapter covers, in the order you'll learn it:
- What a module is and why they're needed
- require() to import a module
- module.exports to export functionality
- Exporting functions
- Exporting objects
- Importing built-in modules
- Module scope (each file is isolated by default)
- Module caching (a module runs once, then is cached)
- Circular dependencies and how to avoid them
2Working Example
๐ป Example: CommonJS Modules
JavaScript
โถ Run in Compiler
// math.js
function add(first, second) {
return first + second;
}
module.exports = { add };
๐ป Continued Example
JavaScript
โถ Run in Compiler
// app.js
const { add } = require("./math");
console.log(add(10, 20));
3Best Practices & Common Pitfalls
๐ก Key things to remember:
- CommonJS is the original, default module system in Node.js and is still extremely common in existing codebases.
- require() calls are synchronous, which is fine for local files but not ideal for network requests.
โ Frequently Asked Questions (FAQ)
Q What's the most important thing to understand about commonjs modules?
Focus on: require() ยท module.exports ยท Module Scope ยท Module Caching ยท Circular Dependencies. These are the core building blocks this chapter's examples are built around, and they show up repeatedly in later chapters of this course.
Q Do I need external npm packages for commonjs modules?
Only where explicitly shown in the code examples above (like Express, Zod, or Socket.IO) โ otherwise, this chapter relies entirely on Node.js's own built-in capabilities.