Chapter 7. Wiring Modules
The Node.js module system brilliantly fills an old gap in the JavaScript language: the lack of a native way of organizing code into different self-contained units. One of its biggest advantages is the ability to link these modules together using the require()
function (as we have seen in
Chapter 2, Node.js Essential Patterns), a simple yet powerful approach. However, many developers new to Node.js might find this confusing; one of the most frequently asked questions is in fact: what's the best way to pass an instance of component X into module Y?
Sometimes, this confusion results in a desperate quest for the Singleton pattern in the hope of finding a more familiar way to link our modules together. On the other hand, some might overuse the Dependency Injection pattern, leveraging it to handle any type of dependency (even stateless) without a particular reason. It should not be surprising that the art of module wiring is one of the most controversial...