At the top of the module I have my log function that will take a mess argument to be logged. I then have a create log once method that when called will return a function that when called will call the utils.log function only once. Any additional calls to the function after that will result in no further action of any kind.
So now it is time to test out this utils module to make sure that it will work they way that I want it to in both a nodejs and bowser environment. So there will need to be at least two basic examples that involve doing a few things in a loop, but only log once for just one item in the loop.
For a nodejs example I just need to require in the utils.js file, and then I can create a single log once method at the top of the file. I can then call the log once method in a while loop, and as I expected a message will only log to the console once.
So that is it for now when it comes to logging something to a console just once. These might not be the most compelling use case examples, but when it comes to working on a real project I often might get around to making some kind of custom logging utility such as this. The feature of having all my logs going to one method helps, and also I am often in a situation in which I just want to log something once when a certain condition happens.
There are many frameworks that might have this kind of method at the ready to begin with though. A few years back I wrote about once such method in lodash which is called the lodash once method. As you would expect that function works more or less the same way, so if a framework that is all ready part of the stack has something like this then there is just making use of what there is to work with to begin with.
There is a lot more to add to this kind of module when it comes to things like the use of color in the output of the log method in a nodejs environment. When it comes to that there is a nodejs npm package called chalk that is a popular solution for that sort of thing, but another option is to just learn a thing or two about ANSI escape codes when it comes to creating color terminal output.
There are maybe just a few more features I might want to add to this kind of module that I might get around to it I come back to this, or start using this module in some actual projects. one such feature is to have control, over the end of line character when using this in a nodejs environment. One way to do so is to make use of the process.stdout.write method in place of console.log if the module is used in a nodejs rather than browser environment. Another idea is that have more than one type of message that can be logged, such as an info and error type where error logs with be logged to the standard error stream, and info type messages will be logged to the standard output. I am sure that even more might pop up if I where to really get into this one, but I have some many other things I would like to work on, and so little time to do so.