简体   繁体   中英

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

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

I've been using the package colors https://www.npmjs.com/package/colors which is very easy to use because it extends String, so for every string you can simply do .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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM