← back to the blog


JavaScript Singleton (using ES6 class)

Posted on April 16th, 2020 in JavaScript by George

 

A singleton ensures a class has only one instance and provides a global point of access to it.

The code speaks better than words so have a look below.

 

//This is the class to provide an object to be used as a Singleton

class PrintMessage {
  constructor() {
    this.logs = [];
  }

  get count() {
    return this.logs.length;
  }

  log(message) {
    const timestamp = new Date().toISOString();
    this.logs.push({message, timestamp});
    console.log(`${timestamp} - ${message}`);
  }
}

//This class will provide the Singleton Instance created from the class above

/*
  In NodeJS you don't need the PrintMessageSingleton class, just using module.exports of an instance 
  'module.exports = new PrintMessage();'
  will cause the module to be cached and treated as a Singleton whenever you are importing it across 
  your application.
*/

class PrintMessageSingleton {
  constructor() {
    if (!PrintMessageSingleton.instance) {
      PrintMessageSingleton.instance = new PrintMessage();
    }
  }

  getInstance() {
    return PrintMessageSingleton.instance;
  }
}



module.exports = PrintMessageSingleton;

 

In NodeJS you don't need the PrintMessageSingleton class, just using module.exports of an instance will cause the module to be cached and treated as a Singleton whenever you are importing it across your application.

For the sake of testing, I have created this test.js file but you can import the message logger as you see fit.

 

const mlog = require('./singleton');
const logger = new mlog().getInstance();

logger.log('wowowow');
logger.log('test with second message');
logger.log('third message');
logger.log(`now check the count please ${logger.count + 1}`);

 

Thank you and stay safe.