问题
Using the chalk library to stylize/colorize the terminal.
import chalk from 'chalk';
if I use:
console.log(chalk.blue('foobar'));
that's totally readable in a terminal with a light background, but totally unreadable in a terminal with a dark background.
Is there some way to determine the background color of a terminal at runtime?
Example given:
The "npm notice"
log level is a case of this problem:
It's difficult to read the blue on black.
回答1:
The following is a generic answer, about ANSI Escape sequences in the tty context.
To highlight a specific sequence by swapping the backgroud/foreground, so it stay readable on all color schemes, use code 7 Reverse video.
This way there is no need to prior knows the palette and adapt.
Example in bash, using reverse video:
echo -e "\033[7mHello world\e[0m"
This can be chained, reverse video, and a red background:
echo -e "\033[31;7mHello world\e[0m"
This will always be readable on any background, like the second line of this gif:
Reverse video is commonly used in software programs as a visual aid to highlight a selection that has been made as an aid in preventing description errors, where an intended action is performed on an object that is not the one intended. It is more common in modern desktop environments to change the background to other colors such as blue, or to use a semi-transparent background to "highlight" the selected text. On a terminal understanding ANSI escape sequences, the reverse video function is activated using the escape sequence CSI 7 m (which equals SGR 7). https://en.wikipedia.org/wiki/Reverse_video
From my own answer: How to change the output color of echo in Linux , a question with a lot of informations about ansi sequences.
来源:https://stackoverflow.com/questions/50027162/determine-terminal-tty-background-color-at-runtime