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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github