Singleton pattern in nodejs - is it needed?

mkoryak picture mkoryak · Nov 1, 2012 · Viewed 83.1k times · Source

I recently came across this article on how to write a singleton in Node.js. I know the documentation of require states that:

Modules are cached after the first time they are loaded. Multiple calls to require('foo') may not cause the module code to be executed multiple times.

So it seems that every required module can be easily used as a singleton without the singleton boilerplate-code.

Question:

Does the above article provide a round about solution to creating a singleton?

Answer

user1046334 picture user1046334 · Nov 1, 2012

All of the above is overcomplicated. There is a school of thought which says design patterns are showing deficiencies of actual language.

Languages with prototype-based OOP (classless) do not need a singleton pattern at all. You simply create a single(ton) object on the fly and then use it.

As for modules in node, yes, by default they are cached, but it can be tweaked for example if you want hot-loading of module changes.

But yes, if you want to use shared object all over, putting it in a module exports is fine. Just do not complicate it with "singleton pattern", no need for it in JavaScript.