Creating singletons in node.js

Nodejs modules are singletons
About 2 minutes read

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() { = 10;

  decrement() {;

  increment() {;

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() {

function increment() {

export default {

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 articles

Clean TypeScript code with type guards

typescripttype guardsclean code

The try/catch and if/else hell

tiinvofunctional programmingclean codeif elsetry catch

Solving a problem with another one.