Node.JS实战41:让命令行变的五颜六色!

通常情况下,命令行文字都是黑底白色的:

想不想来点改变?

给文字换个颜色;给背景换个颜色。

先来看段代码:

console.log('\u001b[31m Hello www.JShaman.com \u001b[0m');
console.log('\u001b[32m Hello www.JShaman.com \u001b[0m');
console.log('\u001b[33m Hello www.JShaman.com \u001b[0m');

想想它的运行输出是什么样的?

猜想到是这个效果了吗?想必没有吧。

为什么看似乱码的一段console()执行时会出现彩色的文字呢?

解释是这样的:

The original specification only had 8 colors, and just gave them names. The SGR parameters 30-37 selected the foreground color, while 40-47 selected the background. Quite a few terminals implemented "bold" (SGR code 1) as a brighter color rather than a different font, thus providing 8 additional foreground colors. Usually you could not get these as background colors, though sometimes inverse video (SGR code 7) would allow that. Examples: to get black letters on white background use ESC[30;47m, to get red use ESC[31m, to get bright red use ESC[31;1m. To reset colors to their defaults, use ESC[39;49m (not supported on some terminals), or reset all attributes with ESC[0m.
SGR code

大意是:“\u001b”是一个特殊的转意字符,遵从一定的规则,可以用来设置文字或背景颜色。

上面代码中,前面的\u001b[31m用于设定SGR颜色,后面的\u001b[0m相当于一个封闭标签作为前面SGR颜色的作用范围的结束点标记。

那么,我们就知道文字变色的原因了。可是如何知道哪个具体的转义字符代表是的什么颜色呢?

下面的操作将进行展示,通过node.js的三方库源码找出答案,熟练掌握此方法将会使你将来大受裨益。

继续:

在Node.JS中,还有一些三方模块,可以实现同样的效果,比如:colors。

例程:

require("colors");

console.log("jshaman.com".green);
console.log("jshaman.com".red);
console.log("jshaman.com".yellow);

运行输出效果:

当安装这个模块后,它的源码就被下载到了本地:

打开这个文件,在代码中会看到:

这下就找道相应颜色的转义字符了。这就是所谓的站在“巨人”的肩膀上吧。

发布了55 篇原创文章 · 获赞 1 · 访问量 652

猜你喜欢

转载自blog.csdn.net/w2sft/article/details/104027270