Search⌘ K

Exporting a Class or Object

Explore how to export single objects or classes from Node.js modules by reassigning module.exports. Understand how to create and use these exports in other files to build modular and maintainable JavaScript code.

We'll cover the following...

Numerous modules in the Node.js ecosystem export only a single object aggregating all of the module’s functionality. To do so, they reassign the module.exports object instead of adding properties to it. For example, check out how the following module calculator.js is defined.

Node.js
// Declare a factory function that returns an object literal
const createCalc = () => {
// The returned object has 4 methods
return {
add(x, y) {
return x + y;
},
substract(x, y) {
return x - y;
},
multiply(x, y) {
return x * y;
},
divide(x, y) {
return x / y;
}
};
};
// Export the factory function
module.exports = createCalc;
...