How to change terminal color in node.js
How can I set terminal font color in node js. I found some modules, but there have limited colors, I want to use any color.
For example. Something like this.
console.log("text", "#87a213");
On this question`s answer are 3 modules, but in these modules colors are limited. I need to print with any color.
Thank You.
You can use ansi-256-colors package. But it does not support any color. But it supports wide range of colors.
To install:
npm install --save ansi-256-colors
To use:
console.log(colors.fg.getRgb(2,3,4) + colors.bg.getRgb(4,4,4) + 'Hello world!' + colors.reset);
You can also use a super simple mixin to add colors support to 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`);
Alternative with no util dependency: (not recommended)
// 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`);
Global version, if you don't want to alter String prototype (this is much much safer )
// 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,所以对于每个字符串,您都可以简单地使用.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
链接地址: http://www.djcxy.com/p/87376.html
下一篇: 如何更改node.js中的终端颜色