node.js – 在运行时确定终端/ TTY背景颜色

使用粉笔库对终端进行样式化/着色.

import chalk from 'chalk';

如果我使用:

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

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

有没有办法在运行时确定终端的背景颜色?

给出的例子:

“npm notice”日志级别是此问题的一个案例:

enter image description here

在黑色上阅读蓝色很难.

最佳答案
以下是一个通用答案,在tty上下文中约为ANSI Escape sequences.

要通过交换背景/前景突出显示特定序列,使其在所有配色方案上保持可读,请使用代码7反向视频.

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

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

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

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

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

这在任何背景上都是可读的,比如这个gif的第二行:

enter image description here

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).
07002

从我自己的答案:How to change the output color of echo in Linux,一个关于ansi序列的大量信息的问题.

转载注明原文:node.js – 在运行时确定终端/ TTY背景颜色 - 代码日志