如何更改node.js中的terminal颜色

如何在节点js中设置terminal字体颜色。 我发现了一些模块,但是颜色有限,我想使用任何颜色。

例如。 像这样的东西。

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

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

你可以使用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); 

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

 // 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`); 

替代scheme没有使用依赖关系:(不推荐)

 // 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`); 

全球版本,如果你不想改变string原型(这是更安全

 // 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`); 

我一直在使用包装colors https://www.npmjs.com/package/colors这是非常容易使用,因为它扩展string,所以对于每一个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