如何在node.js中改变终端颜色



如何在node js中设置终端字体颜色?我找到了一些模块,但是颜色有限,我想用任何颜色

例如

。像这样。

console.log("text", "#87a213");

这个问题的答案有3个模块,但是在这些模块中颜色是有限的。我需要打印任何颜色。
谢谢你。

你也可以使用一个超级简单的mixin来为String prototype添加颜色支持:

// Node String Colors Support (https://git.io/colors)
// Usage console.log("Hello!".green())
const _c = require('util').inspect.colors;
Object.keys(_c).forEach(c =>String.prototype[c] = s =>`x1b[${_c[c][0]}m${s}x1b[${_c[c][1]}m`);

不依赖util的选项:(不推荐)

// Node String Colors Support. (no util version) (https://git.io/colors)
// Usage console.log("Hello!".green())
const _c = {bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};
Object.keys(_c).forEach(c =>String.prototype[c] = s =>`x1b[${_c[c][0]}m${s}x1b[${_c[c][1]}m`); 

全局版本,如果你不想改变字符串原型(这是更安全的)

// Node String Colors Support. (global version) (https://git.io/colors)
// Usage console.log(green("Hello world!")
const _c = require('util').inspect.colors;
Object.keys(_c).forEach(c =>global[c] = s =>`x1b[${_c[c][0]}m${s}x1b[${_c[c][1]}m`);

您可以使用ansi-256-colors包。但是它不支持任何颜色。但是它支持的颜色范围很广。

安装:

npm install --save ansi-256-colors
使用:

console.log(colors.fg.getRgb(2,3,4) + colors.bg.getRgb(4,4,4) + 'Hello world!' + colors.reset);

我一直在使用colors https://www.npmjs.com/package/colors包,它非常容易使用,因为它扩展了String,所以对于每个字符串,您可以简单地执行.red

var colors = require('colors');
console.log('hello'.green); // outputs green text 
console.log('i like cake and pies'.underline.red) // outputs red underlined text 
console.log('inverse the color'.inverse); // inverses the color 
console.log('OMG Rainbows!'.rainbow); // rainbow 
console.log('Run the trap'.trap); // Drops the bass 

最新更新