How to implement Singleton in Node.js


Singleton is object that can have only a single, unique instance, with a single point of access. Node.js module system provides simple way to implement Singleton using module.exports. Module will be cached when it is accessed using require() statement. So our module is merely a cached instance although it behaves like a Singleton.

In this tutorial, we’re gonna look at ways to implement this kind of Singleton in Node.js:

  • Singleton Object
  • Singleton Class

Node.js Singleton Object example

We will create a Bank object, it has 3 methods:
deposit() increases cash.
withdraw() decreases cash.
total() returns cash.


Bank object behaves like a Singleton because we will use module.exports and require() statement (not use new keyword).


As you can see, we create 3 Banks (fund, atm1, atm2), every Bank object can deposit or withdraw money. But all of the action work with only one the cash insides Bank.

Here is the result (run with node app.js command):

Node.js Singleton Class example

Now we will make ScoreBoard like a Singleton.

ScoreBoard object has a board that contains all Players and their scores. Everytime a Player join any Game (we will create more than one Game), he will be added to the board.


You can see that we use require('./ScoreBoard') in many places, because it’s a Singleton, all Players’ scores will be stored at only one place – ScoreBoard object.


Now we create 2 different Game objects with different Player objects to join the game. Each Player win and lose his scores in separated games.

Notice that we use new keyword for creating Game, so Game is not a Singleton, this allows us to create many Game objects.


Run the code with command: node app.js. Here is the result:

Some notes

– Using require() statement is case-insensitive. Inconsistent filenames will cached as separated instances. For example:

– To make Singleton Class, we instantiate the class with new keyword before exporting it out of the module:

By grokonez | March 30, 2019.

Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *