CommonJS Modules

๐ŸŸข Node.js LTS ๐Ÿ“— Chapter 6 of 49 ๐Ÿ“‚ Phase 3: Modules & npm ๐Ÿ—“๏ธ 2026 Edition
๐Ÿ“Œ 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
// math.js
function add(first, second) {
  return first + second;
}

module.exports = { add };
๐Ÿ’ป Continued Example
// 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.

OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Node.js LTS ยท Last updated August 2026