Creating singletons in node.js


A singleton is a common design pattern in object oriented programming.

This pattern forces the program to have only one instance of an object at a time.

In modern JavaScript and TypeScript, lot of developers could create a singleton writing a class and then exporting a single instance of it.

class Foo {
  constructor() {
    this.bar = 10;
  }

  decrement() {
    this.bar--;
  }

  increment() {
    this.bar++;
  }
}

export default new Foo();

Guess what, you are doing it wrong.

In node.js modules are singleton by nature, so you does not need to write a class to it!

Let's rewrite it again:

let bar = 10;

function decrement() {
  bar--;
}

function increment() {
  bar++;
}

export default {
  bar,
  decrement,
  increment,
}

Doing this way is simple and you do not have to create a class (and the machine will not have to instance a unused prototype) and you will avoid to create new instance of Foo class.

Other blog entries