Back to results for “Architecture”
Node.js › Architecture & Design Patterns

What is the Module pattern in Node.js, and how does it enable encapsulation?

Intermediate

Answer

The Module pattern uses each file's own function scope (whether via CommonJS's implicit wrapper function or ESM's module scope) to keep variables and functions private by default, exposing only what's explicitly attached to module.exports or exported via 'export' -- this gives every Node.js file natural encapsulation without needing IIFEs or closures written by hand, unlike plain browser scripts sharing a single global scope.
// counter.js
let count = 0; // private, invisible outside this file

function increment() { count += 1; return count; }
function getCount() { return count; }

module.exports = { increment, getCount };
Real-world example A payment library exposes only a processPayment() function while keeping its internal retry logic, API keys, and validation helpers completely private to the module, preventing consuming applications from accidentally depending on or mutating implementation details that might change between versions.

Common follow-ups: How does this differ from using a class with private fields (#field) for the same encapsulation goal?;What happens to module-level state when the same module is required from multiple files?