How (not) to create a singleton in Node.js
Iain Collins
9628

Use object-to-string to serialize an object gained from a “require” call. This will kill the unwanted caching dilemma. Then deserialize it back to an object so you get an instance at the scope where you are:

var singleton = require(‘./singleton.js’)

var newSingleton = JSON.parse(JSON.stringify(singleton))

The same problem I got just now. It is really important to understand the singleton DEFAULT behavior and purpose of module require pattern. Thanks a lot!

But, maybe requiring with “new” and then initializing on the place is not intuitive anymore to what “require” is for. Besides, I am not sure if this works with the ES6 syntax using “import”.

BTW: this is a shame on JS.

Like what you read? Give Mokhtar Abdu a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.