Learn Node.js design patterns, Singletons in Node

In the last lesson we solved the problem of creating multiple instances of the logger class throughout our application by creating a singleton class and then exporting that class to make sure that we only use one instance of the logger. Implementing the get instance method in a singleton class is pretty typical for an object oriented programming language.

 It’s just fine to implement the singleton this way within Node JS. It’s also nice because it tells other developers that the logger is a singleton. However, there is a easier and more typical solution for singletons in Node JS, and that’s simply to export the instance from the Node JS module.

So, within our exercise files under chapter two, lesson three, I’m going to come into my logger.js file and just implement the singleton an easier way by removing the class. Or the need to export a single class and now on line 19 where I export this module, I’m going to just go ahead and export a new instance of the logger.

The idea here is that when we run this fileit will run once, create the new instance of the logger, and save it in the cache. That means that Node JS will automatically handle exporting the same instance of the logger to every other module that wants to consume it.

So, let’s just go ahead and modify our store.js file. We are going to get rid of line three where we create the instance of the logger here because we’re going to import it directly from our logger module. So, I’ll go ahead and give that a lowercase L so that it matches our logger on line 10. Same thing within our shopper.js file. Let’s get rid of the caw, to new logger, and go ahead and give that a little lowercase L and we will get that instance from our logger module.And then finally the same thing with the index, I’m going to go ahead and import a lowercase logger.

So, we are importing the instance and then I am getting rid of the line where we created the new logger instance. So, I go ahead and save this and we should have the exact same resultswithout the need to create an extra class. So, let’s go ahead and test this out. I’ll come over to the terminal, node index.js, and we see that we have the exact same results, we’re using one logger instance, we’re saving all of the logs, no matter whether they were logged from shopper, store, or our main application.

Leave a Reply

avatar
1000
  Subscribe  
Notify of