Avoid singleton in Node.js? Avoid singleton in Node.js? express express

Avoid singleton in Node.js?


There are cases like this, a passport instance, an express app instance, a mongodb connection pool, a logger instance, etc, where the most common case is a single instance per node process. In these situations, a singleton can be convenient and keep code concise, provided the module also provides an easy way to access and call the constructor for those minority times you want more than one instance (like if your app wants to 2 distinct pools of connections to 2 distinct mongodb databases, or 2 different log streams, for example).

This can sometimes be inconvenient for testing, mocking, stubbing, etc, though.

Is there no way to pass passport var inside controllers from previous code ?

Yes, there is. When you do var passport = require("passport"); you will always get back the exact same singleton instance, including all it's internal state as configured by other code in your application. This is due to the caching that happens in the node require call. What takes extra code is if you want to create a new distinct Passport instance, in which case you need to call the constructor yourself.