在运行时确定 terminal/TTY 背景颜色

Determine terminal/TTY background color at runtime

使用 chalk 库 stylize/colorize 终端。

import chalk from 'chalk';

如果我使用:

console.log(chalk.blue('foobar'));

这在浅色背景的终端中完全可读,但在深色背景的终端中完全不可读。

有什么方法可以在运行时确定终端的背景颜色吗?


给出的例子:

"npm notice" 日志级别就是这个问题的一个例子:

黑底蓝字很难看。

以下是关于 ANSI Escape sequencestty 上下文 .

中的通用答案

要通过交换 backgroud/foreground 突出显示特定序列,使其在所有配色方案上保持可读性,请使用 code 7 Reverse video

这样就不需要事先了解调色板并进行调整。

示例 在 bash 中,使用反向视频:

echo -e "3[7mHello world\e[0m"

这可以链接,反转视频和红色背景:

echo -e "3[31;7mHello world\e[0m"

这将在任何背景下始终可读,例如此 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

来自我自己的回答:How to change the output color of echo in Linux,一个包含很多关于ansi序列.[=16的信息的问题=]