What is CommonJS in Node.js: Explanation and Example
CommonJS is a module system used in Node.js that allows you to organize code into reusable files by using require() to import and module.exports to export. It helps keep code clean and manageable by separating functionality into modules.How It Works
CommonJS works like a set of rules for sharing code between files in Node.js. Imagine each file as a box with tools inside. You can pack tools (functions, objects, or values) into the box using module.exports. Then, in another file, you open that box using require() to use those tools.
This system helps keep your code organized, just like having labeled boxes in a workshop. When you need a specific tool, you just grab the right box instead of mixing everything together.
Example
This example shows how to export a function from one file and import it in another using CommonJS.
// mathUtils.js function add(a, b) { return a + b; } module.exports = { add }; // app.js const mathUtils = require('./mathUtils'); console.log(mathUtils.add(5, 3));
When to Use
Use CommonJS when working with Node.js projects that need modular code. It is the standard module system in Node.js for most versions before ES modules became popular. CommonJS is great for server-side code, scripts, and tools where you want to keep your code clean and reusable.
For example, if you build a web server, a command-line tool, or a backend API, CommonJS helps you split your code into smaller parts that are easier to maintain and test.
Key Points
- CommonJS uses
require()to import andmodule.exportsto export modules. - It is synchronous, meaning modules load one after another.
- CommonJS is the default module system in Node.js before ES modules.
- It helps organize code into reusable pieces.
Key Takeaways
module.exports to export and require() to import modules.