Logo

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

  1. Export a Single Value
    You can assign anything (object, function, class, etc.) to module.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
  2. Export an Object with Multiple Properties
    Often, you want to export multiple functions or variables. One approach is to assign an object to module.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
  3. Using exports as a Shortcut
    Node.js also provides a shorthand: exports. However, it references the same object as module.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 to module.exports. For instance, doing exports = { ... } won’t work as expected.

Tips and Best Practices

  1. 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 to module.exports.

  2. Don’t Overwrite exports
    Reassigning exports directly can lose the original reference to module.exports. If you need to export an entirely new object, always assign to module.exports.

  3. Leverage ES Modules in Modern Node
    Node.js supports ES modules (import / export) if you use a .mjs extension or set "type": "module" in package.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 that require 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 with module.exports.
CONTRIBUTOR
TechGrind