CommonJS Modules
Imagine you're building a large LEGO castle. You don't build it as one giant piece – you build smaller sections (walls, towers, gates) and then connect them. In Node.js, **modules** work the same way. They let you split your code into separate files and connect them together.
What are Modules?
Modules are reusable pieces of code that you can export from one file and import into another. Node.js uses the **CommonJS** module system by default.
Think of modules as separate rooms in a house. Each room has its own purpose, and you can go from one room to another through doors (require statements).
Exporting from a Module
To make code available to other files, you use `module.exports` or `exports`.
Example: math.js (a module)
<!-- Export a single function -->const add = (a, b) => a + b;module.exports = add;
<!-- Or export multiple functions as an object -->const subtract = (a, b) => a - b;const multiply = (a, b) => a * b;
module.exports = { add, subtract, multiply };
<!-- You can also use exports shorthand -->exports.add = add;exports.subtract = subtract;<!-- Note: exports is a reference to module.exports -->Importing with require()
To use code from another module, you use the `require()` function.
Example: app.js (using the math module)
<!-- Import the whole object -->const math = require('./math.js');console.log(math.add(5, 3)); <!-- 8 -->
<!-- Destructure to get specific functions -->const { add, subtract } = require('./math.js');console.log(add(10, 5)); <!-- 15 -->Important Notes
- The path `'./math.js'` means "look in the same directory".
- You can omit the `.js` extension – Node.js adds it automatically.
- For built-in modules (like `fs`, `path`), just use the name without a path: `require('fs')`.
- For npm packages (like `lodash`), also use just the name: `require('lodash')`.
module.exports vs exports
Initially, `exports` is a reference to `module.exports`. So if you reassign `exports`, you break the reference.
<!-- This works -->exports.add = (a, b) => a + b;
<!-- This DOES NOT work – breaks the reference -->exports = { add: (a, b) => a + b }; <!-- ❌ Wrong -->module.exports = { add: (a, b) => a + b }; <!-- ✅ Correct -->Two Minute Drill
- Modules help organize code into separate files.
- Use `module.exports` or `exports` to expose code from a module.
- Use `require()` to import code from another module.
- Built-in and npm packages are imported by name, local files with `./` path.
- CommonJS is Node.js's default module system.
Need more clarification?
Drop us an email at career@quipoinfotech.com
