The module system and its patterns

Modules are the bricks for structuring non-trivial applications, but also the main mechanism to enforce information hiding by keeping private all the functions and variables that are not explicitly marked to be exported. In this section, we will introduce the Node.js module system and its most common usage patterns.

The revealing module pattern

One of the major problems with JavaScript is the absence of namespacing. Programs that run in the global scope polluting it with data that comes from both internal application code and dependencies. A popular technique to solve this problem is called the revealing module pattern, and it looks like the following:

const module = (() => { const privateFoo = () => {...}; const ...

Get Node.js Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.