【发布时间】:2015-12-05 02:37:17
【问题描述】:
如何在节点 js 中设置终端字体颜色。我找到了一些模块,但颜色有限,我想使用任何颜色。
例如。 像这样。
console.log("text", "#87a213");
question 的答案是 3 个模块,但在这些模块中颜色是有限的。我需要用任何颜色打印。
谢谢。
【问题讨论】:
-
@BenFortune 我检查了这个问题。它不能解决我的问题,因为他们使用的颜色有限
如何在节点 js 中设置终端字体颜色。我找到了一些模块,但颜色有限,我想使用任何颜色。
例如。 像这样。
console.log("text", "#87a213");
question 的答案是 3 个模块,但在这些模块中颜色是有限的。我需要用任何颜色打印。
谢谢。
【问题讨论】:
你还可以使用一个超级简单的 mixin 来为字符串原型添加颜色支持:
// 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);
【讨论】:
我一直在使用包colorshttps://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
【讨论】: