What is the purpose of Node.js module.exports and how do you use it?
In Node.js, every file is treated as a separate module. The module.exports
object defines what a module makes available to other modules when they use require(...)
to import it. It’s part of Node’s CommonJS module system.
Why module.exports
Matters
- It encapsulates the functionality or data in a module.
- It exposes only what you explicitly specify, keeping the rest private to your file.
- It allows you to import and reuse functionality across multiple files in your Node.js application.
Basic Usage
-
Export a Single Value
You can assign anything (object, function, class, etc.) tomodule.exports
:// math.js function add(a, b) { return a + b; } module.exports = add; // Export this function
Then in another file:
// main.js const add = require('./math'); console.log(add(2, 3)); // 5
-
Export an Object with Multiple Properties
Often, you want to export multiple functions or variables. One approach is to assign an object tomodule.exports
:// math.js function add(a, b) { return a + b; } function subtract(a, b) { return a - b; } module.exports = { add, subtract };
And then:
// main.js const { add, subtract } = require('./math'); console.log(add(5, 2)); // 7 console.log(subtract(5, 2)); // 3
-
Using
exports
as a Shortcut
Node.js also provides a shorthand:exports
. However, it references the same object asmodule.exports
at the start, so you can do:// math.js exports.add = (a, b) => a + b; exports.subtract = (a, b) => a - b;
But be careful not to overwrite
exports
itself, or you might break the reference tomodule.exports
. For instance, doingexports = { ... }
won’t work as expected.
Tips and Best Practices
-
Choose One Style
Consistency in code is key. If your module exports multiple methods, consider the object-literal style. If you export just one main function or class, assign it directly tomodule.exports
. -
Don’t Overwrite
exports
Reassigningexports
directly can lose the original reference tomodule.exports
. If you need to export an entirely new object, always assign tomodule.exports
. -
Leverage ES Modules in Modern Node
Node.js supports ES modules (import
/export
) if you use a.mjs
extension or set"type": "module"
inpackage.json
. This is an alternative approach if you prefer the newer syntax.
Recommended Resource
Summary
module.exports
determines what a Node.js module makes available to other modules thatrequire
it.- You can export functions, objects, classes, or any data type by assigning them to
module.exports
. exports
is a shorthand that references the same object initially but should not be overwritten entirely if you want to keep it in sync withmodule.exports
.