Skip to content
Advertisement

Log to console only when run from cli command

I’m currently developing a node js cli tool to do some random stuff for work. Up until this point, my whole app was designed as a cli without any intention to use its functionality somewhere else.

Now some of my collegues like to work with a ui instead of a cli so I decited to build a vue web app around it. SO far so good.

Now my problem: I plastered all of my functions with console.logs and packages like cliui, chalk, inquirer, etc. This obviously makes no sense when used as a module in a vue app.

My question is: How do I log output from individual functions only when used via cli?

One idea I have is to set some kind of falgg in my command function so the process knows I’m in a terminal and check for every console.log if that flag is set. But that seems to be a lot of work and I wonder if there is a better way.

Advertisement

Answer

I would strongly suggest to use some logging library, like for instance winston. There you can define multiple so called transports, which are responsible for writing the logs in the respective specified location (for instance a file, a database or just the console). Then do all your logging only through this library.

So you will have a single point in the very beginning of your app, where you can define whether to activate a transport to the console or not …

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement