Course contentsShow
← JavaScript
Lesson 1439 of 2,72331. ModulesFree lesson

Module.exports: Exporting from a File

Understand how module.exports defines what a file makes available to other files.

Module.exports: Exporting from a File

You'll learn how module.exports makes values available for other files to use in CommonJS modules.

The Core Idea

In CommonJS (Node.js's original module system), each file is its own private world. By default, nothing inside a file is visible to other files. module.exports is the gatekeeper — it's a special object that defines exactly what your file shares with the outside world.

Think of it like a storefront: everything you create inside your shop (variables, functions, objects) stays private in the back room. module.exports is your display window — only what you put there is visible and available to customers (other files).

How It Works

Every file in CommonJS automatically has a module object with an exports property. Whatever you assign to module.exports becomes the "return value" of that file when another file loads it:

// calculator.js
const pi = 3.14159;

function add(a, b) {
  return a + b;
}

function multiply(a, b) {
  return a * b;
}

// Only these are visible to other files
module.exports = {
  add: add,
  multiply: multiply
};

// pi remains private

You can export a single function, an object with multiple properties, a class, or any JavaScript value. Whatever you assign last to module.exports is what other files will receive when they import your module.

// single function export
module.exports = add;

// or exporting a class
module.exports = Calculator;

Key Takeaway: module.exports is CommonJS's way of explicitly declaring what a file makes public — anything not assigned to it stays private and encapsulated within the module.