0

I use ANSI colorized text output in logs and other output that I emit on stderr in some of my programs. Since I've been doing this kind of thing for years, I am pretty familiar with the capabilities.

The trouble with the change in behavior that node.js introduced is that now all stderr output is getting wrapped in red foreground (text) color codes, and it's generally not practical or possible to refactor entire applications to become aware of whether this thing is going to happen to the stderr stream or not. If I am emitting some output with some colored text, e.g. Error:\e[33m message\e[39m at position

That writes "Error: message at position" where "message" is in yellow. When node.js causes this whole thing to be then wrapped in \e[31m \e[m (or \e39m), what I will end up with on the terminal is "Error:" in red, "message" in yellow, and "at position" in the normal text color. This is unexpected and looks wrong, but basically it's impossible to fix unless I change the behavior of my code to know it is emitting this on stderr and if it knows that the version of node running the code is new enough it should change to red text color instead of resetting the text color.

One way to express this issue is the fact that ANSI escapes are a stream protocol instead of being a tree/stack like HTML or something, whereby the yellow color could be popped leaving the base red color there.

One approach I could take is to change to not use text colors in stderr output, as the ansi states for background color, boldedness, italicness, etc. are not going to mess with the red text color when they get reset with their appropriate reset codes.

This is still not ideal though, because I definitely have situations where I want the colorized util.inspect strings in certain error outputs...

4
  • I guess this is just motivation for me to add a layer of abstraction that knows which way to reset colors in these strings. I should be able to key the behavior off of process.version to make sure it happens only on the right environments. Commented Jun 19, 2024 at 16:53
  • 1
    Some terminal emulators support XTPUSHSGR (\e[#{) and XTPOPSGR (\e[#}) to save and restore the attributes (e.g. text color). See XTerm's ctlseqs documentation for details. Commented Jun 19, 2024 at 17:02
  • Another obvious approach is to begin your message with \e[m, that way you override node.js's new behavior of wrapping in red and take back full control over the attributes. Commented Jun 20, 2024 at 5:03
  • Thanks, I didn't even think about switching to spamming a clear at the front. What's otherwise mild protocol bloat really comes in handy for this situation. The save/restore is also a helpful tip thank you. Commented Jun 25, 2024 at 20:37

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.