What is the purpose of Node.js module.exports and how do you use it?

Better Stack Team
Updated on March 11, 2024

In Node.js, module.exports is a special object that is used to define what a module exports as its public interface. It is used to expose functionality from one module (file) to another module, allowing you to encapsulate and organize your code into reusable and maintainable units.

Here's how you can use module.exports:

Exporting a Single Function or Object:

 
// math.js
const add = (a, b) => a + b;
module.exports = add;

In another file:

 
// app.js
const addFunction = require('./math.js');
console.log(addFunction(2, 3)); // Outputs: 5

Exporting Multiple Functions or Objects:

 
// math.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;

module.exports = {
  add,
  subtract
};

In another file:

 
// app.js
const mathFunctions = require('./math.js');
console.log(mathFunctions.add(2, 3)); // Outputs: 5
console.log(mathFunctions.subtract(5, 3)); // Outputs: 2

Exporting as Named Variables:

 
// math.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;

module.exports.add = add;
module.exports.subtract = subtract;

In another file:

 
// app.js
const mathFunctions = require('./math.js');
console.log(mathFunctions.add(2, 3)); // Outputs: 5
console.log(mathFunctions.subtract(5, 3)); // Outputs: 2

Shorthand for Named Exports:

 
// math.js
exports.add = (a, b) => a + b;
exports.subtract = (a, b) => a - b;

In another file:

 
// app.js
const mathFunctions = require('./math.js');
console.log(mathFunctions.add(2, 3)); // Outputs: 5
console.log(mathFunctions.subtract(5, 3)); // Outputs: 2

module.exports is crucial for organizing code into reusable and manageable modules in Node.js. It allows you to expose specific functions, objects, or variables from a module and make them accessible to other parts of your application.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.