962

I had to change the console background color to white because of eye problems, but the font is gray colored and it makes the messages unreadable. How can I change it?

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
MaiaVictor
  • 51,090
  • 44
  • 144
  • 286
  • 4
    In the same place you already used to change the background color, you can change the other colors. – Dan D. Mar 20 '12 at 20:44
  • 1
    I'm having the same problem. I suspect @Viclib is using windows (as am I), which is why instructions to change terminal colors are a foreign concept. The windows command prompt allows changing 2 foreground and 2 background colors. Node uses other colors which windows command prompt cannot define. – Greg Woods Apr 07 '15 at 09:25
  • @GregWoods. the accepted answer below does work in Windows ! – joedotnot Dec 15 '18 at 15:38
  • 2
    I later discovered that my mental model for how Windows command prompt colours worked, was completely wrong. I assumed incorrectly (due to a terrible UI) that you can only change foreground, background colours. This is wrong. All 16 colours can be used by a console app, and it is vital to pick sensible colours for all 16, and to ALWAYS use colour tile 1 as background (and tile 9 for "popup background"). This was such a revelation to me, I wrote a blog post (a rare event indeed). http://gregwoods.co.uk/2015/04/using-windows-command-prompt-colours-with-node-js/ – Greg Woods Dec 20 '18 at 14:29
  • @GregWoods That blog post link is dead now – kungfooman May 21 '22 at 14:54

39 Answers39

2048

Below you can find colors reference of text to command when running node.js application:

console.log('\x1b[36m%s\x1b[0m', 'I am cyan');  //cyan
console.log('\x1b[33m%s\x1b[0m', stringToMakeYellow);  //yellow

Note %s is where in the string (the second argument) gets injected. \x1b[0m resets the terminal color so it doesn't continue to be the chosen color anymore after this point.

Colors reference

Reset = "\x1b[0m"
Bright = "\x1b[1m"
Dim = "\x1b[2m"
Underscore = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"

FgBlack = "\x1b[30m"
FgRed = "\x1b[31m"
FgGreen = "\x1b[32m"
FgYellow = "\x1b[33m"
FgBlue = "\x1b[34m"
FgMagenta = "\x1b[35m"
FgCyan = "\x1b[36m"
FgWhite = "\x1b[37m"
FgGray = "\x1b[90m"

BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"
BgGray = "\x1b[100m"

EDIT:

For example, \x1b[31m is an escape sequence that will be intercepted by your terminal and instructs it to switch to the red color. In fact, \x1b is the code for the non-printable control character escape. Escape sequences dealing only with colors and styles are also known as ANSI escape code and are standardized, so therefore they (should) work on any platform.

Wikipedia has a nice comparison of how different terminals display colors https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

Raine Revere
  • 30,985
  • 5
  • 40
  • 52
Bud Damyanov
  • 30,171
  • 6
  • 44
  • 52
  • 95
    I've accepted this question because it is the laziest one that works, has many colors and no dependencies. If you want simpler solution *with* dependencies, check @nelsonic's answer which suggests very straightforward libs. – MaiaVictor Feb 16 '17 at 15:00
  • 9
    Where did you find this reference? What does every character in a color value mean ? – giorgos.nl May 03 '17 at 08:55
  • 14
    @giorgos29cm [→ see here](http://bluesock.org/~willkg/dev/ansi.html). Btw, add an `1;` for bright colors, i.e. "\x1b[1;34m" == light blue... – Frank N Oct 24 '17 at 13:35
  • 3
    How should I prevent these characters from showing when printing to file rather than console? – Sky Mar 29 '18 at 20:45
  • 1
    Curiously, on Windows 10 powershell the yellow turns up as white? Yellow can be made to work; [chalk](https://www.npmjs.com/package/chalk) does it. However, this answer saved me from adding chalk as a dependency for a few measly logs, thanks! – webelo Jan 09 '19 at 14:22
  • 3
    I've taken this answer and changed it slightly to be runnable code. https://stackoverflow.com/a/57100519/4808079 – Seph Reed Jul 18 '19 at 18:19
  • For the record, this has been lifted directly into an external article here: http://voidcanvas.com/make-console-log-output-colorful-and-stylish-in-browser-node/ – random_user_name Sep 24 '19 at 20:52
  • @MaiaVictor complex syntax is not lazy, nor easy to remember. For a simple trick, similar to chalk but with more minimalist syntax check [`borodinmk`'s answer](https://stackoverflow.com/a/35483907/6253165) using the npm package **[paint-console](https://www.npmjs.com/package/paint-console)**. – nilon Jan 06 '20 at 13:25
  • You can check the [Emoji answer](https://stackoverflow.com/a/59344322/5623035).It’s supported out of the box without any dependencies. Also have some cool advantages. – Mojtaba Hosseini Jul 24 '20 at 23:43
  • What about the orange color? – David Callanan Aug 07 '20 at 10:00
  • @Sky Use `console.log(Color + "Text" + Reset)` instead of `console.log(Color, "Text", Reset)` to prevent automatically added spaces – Michael Clark Jan 03 '23 at 16:22
  • is it crossplatform? say if I do `'\x1b[31m' + mytext + '\x1b[0m';` will it work in all terminals across all OS's or there some limitations? – angularrocks.com Feb 18 '23 at 02:15
  • As Henry Tseng mentions, you are missing a piece to bring back the terminal colour to default, otherwise it stays on the last colour used: `console.log('\x1b[36m', 'sometext' ,'\x1b[0m');` – Bru Mas Ribera Mar 11 '23 at 12:00
479

There are multiple packages available for formatting console text in Node.js. The most popular are:

Usage:

CHALK:

const chalk = require('chalk');
console.log(chalk.red('Text in red'));

CLI-COLOR:

const clc = require('cli-color');
console.log(clc.red('Text in red'));

nelsonic
  • 31,111
  • 21
  • 89
  • 120
  • 1
    It even has simple lightweight support for styles! – hippietrail Feb 14 '13 at 12:23
  • 2
    @devundef agree with you on adding methods to the String object. Might be worth mentioning that to the module author on GitHub. And/Or suggesting an alternative module/method with similar level of simplicity. – nelsonic Jul 11 '13 at 06:11
  • 4
    While I agree that MattJohnson's answer (overriding the util.inpect method's default colors - see below) is better than using the Colors module, the Colors module requires *zero setup* and fits the needs of the *vast majority of users* which is simply changing color of console.log output. Sure, "messing with built-ins" is bad (agree 100%) but no *deployed* code should contain console.log statements, so lets be pragmatic about this. @devundef Do the extra String methods added to the prototype mess with your unit tests? – nelsonic Jan 22 '14 at 23:54
  • 8
    Colors has that now: `var colors = require('colors/safe');` and then use `colors.red('left string all alone')` – Laoujin Apr 29 '15 at 20:20
  • 1
    When I `require` `chalk` I get: `Error [ERR_REQUIRE_ESM]: require() of ES Module [omitted]\node_modules\chalk\source\index.js from [omitted].js not supported.` – Jesus is Lord Dec 22 '21 at 15:53
  • 1
    @JesusisLord Chalk is pure ESM since v5.0.0. You should be fine using v4.1.2. `npm i chalk@4.1.2` – VibingCreator Dec 21 '22 at 17:03
224

If you want to change the colors directly yourself without a module try

console.log('\x1b[36m', 'sometext' ,'\x1b[0m');

First \x1b[36m to change the colors to 36 and then back to terminal color 0.

Here's a list of ANSI color codes

Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
Henry Tseng
  • 3,263
  • 1
  • 19
  • 20
99

This is a list of available colours (both background and foreground) in the console with some available actions (like reset, reverse, etc).

const colours = {
    reset: "\x1b[0m",
    bright: "\x1b[1m",
    dim: "\x1b[2m",
    underscore: "\x1b[4m",
    blink: "\x1b[5m",
    reverse: "\x1b[7m",
    hidden: "\x1b[8m",
    
    fg: {
        black: "\x1b[30m",
        red: "\x1b[31m",
        green: "\x1b[32m",
        yellow: "\x1b[33m",
        blue: "\x1b[34m",
        magenta: "\x1b[35m",
        cyan: "\x1b[36m",
        white: "\x1b[37m",
        gray: "\x1b[90m",
        crimson: "\x1b[38m" // Scarlet
    },
    bg: {
        black: "\x1b[40m",
        red: "\x1b[41m",
        green: "\x1b[42m",
        yellow: "\x1b[43m",
        blue: "\x1b[44m",
        magenta: "\x1b[45m",
        cyan: "\x1b[46m",
        white: "\x1b[47m",
        gray: "\x1b[100m",
        crimson: "\x1b[48m"
    }
};

Here's an example of how to use it:

console.log(colours.bg.blue, colours.fg.white, "I am a white message with a blue background", colours.reset) ; 
// Make sure that you don't forget "colours.reset" at the so that you can reset the console back to it's original colours.

Or you can install some utility modules:

npm install console-info console-warn console-error --save-dev

These modules will show something like the following to the console when you use them:

Example of the utility modules that I've mentioned.

Raine Revere
  • 30,985
  • 5
  • 40
  • 52
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • 2
    I am using the same and works fine but for some reason Dim doesn't do anything? I want the grey color effect so thought would use white color with dim effect would result in grey color but only white color prints no dim. Any idea? – Angad Aug 01 '18 at 11:32
  • Unfortunately, using it like this in a console creates lots of spaces. – Qwerty Mar 19 '21 at 06:54
  • Use `+` instead of `, ` in-between the colours to avoid the spaces – orta May 07 '21 at 11:13
  • 1
    Crimson doesn't exit in console! – synkro Oct 09 '21 at 18:03
  • 1
    Solution with npm packages (console-info console-warn console-error): don't forget to require packages in your js files (e.g. require('console-info');) – Nicolas Bodin Nov 16 '22 at 15:00
  • The first solution is the only one which works for me. Can I pass foreground color only and leave the background as the default color? – CodeMonkey Jun 14 '23 at 09:28
  • There's also an issue with the first solution which doesn't color all the lines of a multi lines text, but only the first line – CodeMonkey Jun 15 '23 at 08:17
76

to color your output You can use examples from there:
https://help.ubuntu.com/community/CustomizingBashPrompt

Also a Gist for nodeJs

For example if you want part of the text in red color, just do console.log with:

"\033[31m this will be red \033[91m and this will be normal"

Based on that I've created "colog" extension for Node.js. You can install it using:

npm install colog

Repo and npm: https://github.com/dariuszp/colog

Shanimal
  • 11,517
  • 7
  • 63
  • 76
Dariuszp
  • 785
  • 5
  • 2
  • 1
    I believe the OP does not want to print specific text in a specific color but all Terminal output to be in a different color by default, maybe even black given the white background. – cwoebker Jul 08 '13 at 10:42
  • Then he should change settings of his terminal. I'm sure it is possible on Linux. No idea about Windows. – Dariuszp Jul 08 '13 at 11:33
  • Changing the Theme of the terminal/console on Linux/Mac is easy. Just select (or create) your theme in Preferences. Windows. not so much... – nelsonic Jul 11 '13 at 06:13
  • 16
    `\033[31m` works but `\033[91m` doesn't. For Ubuntu Terminal it should be `\033[0m`. – Redsandro Jan 13 '14 at 15:49
  • 4
    And octal escapes don't appear to work: `error: octal escape sequences "\033[31mServer ready @ #{app.get('port')}\033[91m" are not allowed` – jcollum Feb 13 '14 at 19:28
  • 4
    `\033[0m` should be used to turn the text back to normal, not `\033[91m` – mollerhoj Aug 18 '14 at 14:16
  • lightweight alternative. Love it! – schlenger Oct 24 '14 at 21:10
  • BTW, check this link for more ANSI color codes. https://help.ubuntu.com/community/CustomizingBashPrompt – Lewis Nov 16 '14 at 10:22
  • 1
    This will cause a `SyntaxError: Octal literals are not allowed in strict mode.` "The issue was caused by ANSI escape code which is a string, not a number (octal literal) that starts with 0, like 0644. In my case the string was '\033[0m'. The solution was to replace it with '\u001b[0m'" - https://github.com/TypeStrong/ts-node/issues/90#issue-144783379 – craigmichaelmartin Aug 26 '16 at 15:03
46

Color codes are as mentioned

Reset: "\x1b[0m"
Bright: "\x1b[1m"
Dim: "\x1b[2m"
Underscore: "\x1b[4m"
Blink: "\x1b[5m"
Reverse: "\x1b[7m"
Hidden: "\x1b[8m"

FgBlack: "\x1b[30m"
FgRed: "\x1b[31m"
FgGreen: "\x1b[32m"
FgYellow: "\x1b[33m"
FgBlue: "\x1b[34m"
FgMagenta: "\x1b[35m"
FgCyan: "\x1b[36m"
FgWhite: "\x1b[37m"
FgGray: "\x1b[90m"

BgBlack: "\x1b[40m"
BgRed: "\x1b[41m"
BgGreen: "\x1b[42m"
BgYellow: "\x1b[43m"
BgBlue: "\x1b[44m"
BgMagenta: "\x1b[45m"
BgCyan: "\x1b[46m"
BgWhite: "\x1b[47m"
FgGray: "\x1b[100m"

For example if you want to have a Dim, Red text with Blue background you can do it in Javascript like this:

console.log("\x1b[2m", "\x1b[31m", "\x1b[44m", "Sample Text", "\x1b[0m");

The order of the colors and effects seems to not be that important but always remember to reset the colors and effects at the end.

Raine Revere
  • 30,985
  • 5
  • 40
  • 52
Shnd
  • 1,846
  • 19
  • 35
  • @Sergey blink also doesn't work for me, seems like it isn't available in Node – Sv443 Dec 07 '18 at 15:45
  • @Sv443 But it works on the screenshot :) And the question was about Node. I thought it didn't work only in Windows console. What OS do you use? – Serg Dec 07 '18 at 16:16
  • 2
    @Sergey I am using Windows and tried in CMD and Powershell and both don't work – Sv443 Dec 07 '18 at 21:35
  • @Sergey My screenshots are from MacOS terminal application. I believe this is something that your shell application should support. If you're using windows, I would suggest try to install Cygwin and try this on bash. I'm curious to know about this too. – Shnd Dec 08 '18 at 19:07
  • @Shnd I'm not sure whether it's the same, but I tried it on git-bash and it didn't work either. – Serg Dec 27 '18 at 12:58
44

Emoji

You can use colors for text as others mentioned in their answers.

But you can use emojis instead! for example, you can use⚠️ for warning messages and for error messages.

Or simply use these notebooks as a color:

: error message
: warning message
: ok status message
: action message
: canceled status message
: Or anything you like and want to recognize immediately by color

Bonus:

This method also helps you to quickly scan and find logs directly in the source code.

for example:

console.log('Bring with ❤️ to you from Mojtaba Hosseini');

Some Linux distributions default emoji font may not be colorful by default and you may want to make them colorful, first.


How to open emoji picker?

mac os: control + command + space

windows: win + .

linux: control + . or control + ;

Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
38

Per this documentation, you can change the colors based on the data type of the output:

// you'll need the util module
var util = require('util');

// let's look at the defaults: 
util.inspect.styles

{ special: 'cyan',
  number: 'yellow',
  boolean: 'yellow',
  undefined: 'grey',
  null: 'bold',
  string: 'green',
  date: 'magenta',
  regexp: 'red' }

// what are the predefined colors?
util.inspect.colors

{ 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 ] }

These appear to be ANSI SGR escape codes, where the first number is the code to emit before the output, and the second number is the code to emit after. So if we look at the chart of ANSI SGR codes on Wikipedia, you'll see that most of these start with a number 30-37 to set the foreground color, and end in 39 to reset to the default foreground color.

So one thing I don't like is how dark some of these are. Especially dates. Go ahead and try new Date() in the console. Dark magenta on black is really hard to read. Let's change that to a light magenta instead.

// first define a new color
util.inspect.colors.lightmagenta = [95,39];

// now assign it to the output for date types
util.inspect.styles.date = 'lightmagenta';

Now when you try new Date(), the output is much more readable.

If you'd like to set colors automatically when launching node, create a script that launches the repl, like this:

// set your colors however desired
var util = require('util');
util.inspect.colors.lightmagenta = [95,39];
util.inspect.styles.date = 'lightmagenta';

// start the repl    
require('repl').start({});

Save this file (for example, init.js), then run node.exe init.js. It will set the colors and launch the node.js command prompt.

(Thanks to loganfsmyth in this answer for the repl idea.)

Community
  • 1
  • 1
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
36

I found this answer above (https://stackoverflow.com/a/41407246/4808079) very useful, but incomplete. If you only ever wanted to color something once, I guess it'd be fine, but I think sharing it in a runnable functional form is much more applicable to real life use cases.

const Color = {
  Reset: "\x1b[0m",
  Bright: "\x1b[1m",
  Dim: "\x1b[2m",
  Underscore: "\x1b[4m",
  Blink: "\x1b[5m",
  Reverse: "\x1b[7m",
  Hidden: "\x1b[8m",
  
  FgBlack: "\x1b[30m",
  FgRed: "\x1b[31m",
  FgGreen: "\x1b[32m",
  FgYellow: "\x1b[33m",
  FgBlue: "\x1b[34m",
  FgMagenta: "\x1b[35m",
  FgCyan: "\x1b[36m",
  FgWhite: "\x1b[37m",
  FgGray: "\x1b[90m",
  
  BgBlack: "\x1b[40m",
  BgRed: "\x1b[41m",
  BgGreen: "\x1b[42m",
  BgYellow: "\x1b[43m",
  BgBlue: "\x1b[44m",
  BgMagenta: "\x1b[45m",
  BgCyan: "\x1b[46m",
  BgWhite: "\x1b[47m"
  BgGray: "\x1b[100m",
}

function colorString(color, string) {
  return `${color}${string}${Color.Reset}`;
}

function colorLog(color, ...args) {
  console.log(...args.map(
   (it) => typeof it === "string" ? colorString(color, string) : it
  ));
}

Use it like this:

colorLog(Color.FgYellow, "Some Yellow text to console log", { someObj: true });

console.log([
  colorString(Color.FgRed, "red"),
  colorString(Color.FgGreen, "green"),
  colorString(Color.FgBlue, "blue"),
].join(", "));
Raine Revere
  • 30,985
  • 5
  • 40
  • 52
Seph Reed
  • 8,797
  • 11
  • 60
  • 125
31

If you want to keep it SIMPLE without using any external module / learn new APIs / hacking the core console functions:

const LCERROR = '\x1b[31m%s\x1b[0m'; //red
const LCWARN = '\x1b[33m%s\x1b[0m'; //yellow
const LCINFO = '\x1b[36m%s\x1b[0m'; //cyan
const LCSUCCESS = '\x1b[32m%s\x1b[0m'; //green

const logger = class {
  static error(message, ...optionalParams) { console.error(LCERROR, message, ...optionalParams) }
  static warn(message, ...optionalParams) { console.warn(LCWARN, message, ...optionalParams) }
  static info(message, ...optionalParams) { console.info(LCINFO, message, ...optionalParams) }
  static success(message, ...optionalParams) { console.info(LCSUCCESS, message, ...optionalParams) }
}

// then instead (as presented in the accepted answer)
// console.error(LCERROR, 'Error message in red.');
// you write:

logger.error('Error message in red.');

// or with multiple parameters (only the message will be red):

logger.error('Error message in red.', 1, false, null, {someKey: 'whatever'});

// or use backticks (template literal) instead multiple params:

logger.error(`This will be red as ${foo} and ${bar} too.`);

Now you can use your logger in the same way as you would with console. There's no new API to remember... Normally you would put it into a module (logger.js) and export the class to be able to use it everywhere in your app as const logger = require('./logger');

szegheo
  • 4,175
  • 4
  • 31
  • 35
30

A handy one-liner I wrote for npm scripts that can't have dependencies:

const { r, g, b, w, c, m, y, k } = [
  ['r', 1], ['g', 2], ['b', 4], ['w', 7],
  ['c', 6], ['m', 5], ['y', 3], ['k', 0],
].reduce((cols, col) => ({
  ...cols,  [col[0]]: f => `\x1b[3${col[1]}m${f}\x1b[0m`
}), {})

console.log(`${g('I')} love ${r('Italy')}`)

r,g,b,w,c,m,y,k stands for red, green, blue, white, cyan, magenta, yellow and black.

Pang
  • 9,564
  • 146
  • 81
  • 122
chriskelly
  • 7,526
  • 3
  • 32
  • 50
24

This library by Sindre Sorhus is the best at the moment:

chalk

  • Highly performant
  • Doesn't extend String.prototype
  • Expressive API
  • Ability to nest styles
  • Clean and focused
  • Auto-detects color support
  • Actively maintained
  • Used by 5500+ modules
dthree
  • 19,847
  • 14
  • 77
  • 106
callum
  • 34,206
  • 35
  • 106
  • 163
  • 6
    yeah but its another dependency – wayofthefuture May 10 '18 at 12:28
  • Don't use this library if you're using jest/ts-jest because compilation raises some annoying to debug issues. You'll end up add all sorts of weird and wonderful adjustments to your config file due to ansi and dynamic imports. IMHO create an abstraction and use a dependency free version. – Roland Fuchs Sep 03 '22 at 09:46
13

No libraries no complications just simple:

console.log(red('Error!'));

function red(s) {
    return '\033[31m' + s;
}
wayofthefuture
  • 8,339
  • 7
  • 36
  • 53
  • 3
    It isn't simple when you find out that it doesn't work with objects the way console handles them, and that it doesn't respect the console stream types or TTY support, which creates further problems. It is just a hack that will bring lots of problems down the road. – vitaly-t Aug 17 '17 at 09:45
  • That's what JSON.stringify is for – wayofthefuture May 10 '18 at 12:29
  • @wayofthefuture "it doesn't work with objects the way console handles them" means we can expand and collapse the object. – Manohar Reddy Poreddy Feb 17 '21 at 00:39
12

For a popular alternative to colors that doesn't mess with the built-in methods of the String object, I recommend checking out cli-color.

Includes both colors and chainable styles such as bold, italic, and underline.

For a comparison of various modules in this category, see here.

user456584
  • 86,427
  • 15
  • 75
  • 107
10

I overloaded the console methods.

var colors={
Reset: "\x1b[0m",
Red: "\x1b[31m",
Green: "\x1b[32m",
Yellow: "\x1b[33m"
};

var infoLog = console.info;
var logLog = console.log;
var errorLog = console.error;
var warnLog = console.warn;

console.info= function(args)
{
    var copyArgs = Array.prototype.slice.call(arguments);
    copyArgs.unshift(colors.Green);
    copyArgs.push(colors.Reset);
    infoLog.apply(null,copyArgs);
};

console.warn= function(args)
{
    var copyArgs = Array.prototype.slice.call(arguments);
    copyArgs.unshift(colors.Yellow);
    copyArgs.push(colors.Reset);
    warnLog.apply(null,copyArgs);
};
console.error= function(args)
{
    var copyArgs = Array.prototype.slice.call(arguments);
    copyArgs.unshift(colors.Red);
    copyArgs.push(colors.Reset);
    errorLog.apply(null,copyArgs);
};

// examples
console.info("Numeros",1,2,3);
console.warn("pares",2,4,6);
console.error("reiniciandooo");

The output is.

enter image description here

Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
Ronald Coarite
  • 4,460
  • 27
  • 31
  • This doesn't work with the formatting syntax. Example: `console.info('Hello %s', 'World!')` is supposed to display `Hello World!`, and not `Hello %s World!`. – vitaly-t Aug 17 '17 at 09:56
  • @vitaly-t try **[this](https://stackoverflow.com/a/52670481/1844247)**: it should work. – Serg Oct 05 '18 at 17:19
8

Came across this question, and wanted to use some colors on stdout without any dependencies. This combines some of the other great answers here.

Here's what I've got. (Requires node v4 or greater)

// colors.js
const util = require('util')

function colorize (color, text) {
  const codes = util.inspect.colors[color]
  return `\x1b[${codes[0]}m${text}\x1b[${codes[1]}m`
}

function colors () {
  let returnValue = {}
  Object.keys(util.inspect.colors).forEach((color) => {
    returnValue[color] = (text) => colorize(color, text)
  })
  return returnValue
}

module.exports = colors()

Just require the file, then use it like so:

const colors = require('./colors')
console.log(colors.green("I'm green!"))

The predefinied color codes are available here

Joseph Post
  • 101
  • 1
  • 3
8

There are two ways to look at changing colors for a Node.js console today.

One is through general-purpose libraries that can decorate a text string with color tags, which you then output through the standard console.log.

The top libraries for that today:

And the other way - patching the existing console methods. One such library - manakin lets you automatically set standard colors for all your console methods (log, warn, error and info).

One significant difference from the generic color libraries - it can set colors either globally or locally, while keeping consistent syntax and output format for every Node.js console method, which you then use without having to specify the colors, as they are all set automatically.

I had to change the console background color to white because of eye problems, but the font is gray colored and it makes the messages unreadable. How can I change it?

Specifically for your problem, here's the simplest solution:

var con = require('manakin').global;
con.log.color = 30; // Use black color for console.log

It will set black color for every console.log call in your application. See more color codes.

Default colors as used by manakin:

enter image description here

vitaly-t
  • 24,279
  • 15
  • 116
  • 138
7

paint-console

Simple colorable log. Support inspect objects and single line update This package just repaint console.

install

npm install paint-console

usage

require('paint-console');

console.info('console.info();');
console.warn('console.warn();');
console.error('console.error();');
console.log('console.log();');

demo

borodinmk
  • 109
  • 1
  • 3
7

I don't want any dependency for this and only these worked for me on OS X. All other samples from answers here gave me Octal literal errors.

Reset = "\x1b[0m"
Bright = "\x1b[1m"
Dim = "\x1b[2m"
Underscore = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"

FgBlack = "\x1b[30m"
FgRed = "\x1b[31m"
FgGreen = "\x1b[32m"
FgYellow = "\x1b[33m"
FgBlue = "\x1b[34m"
FgMagenta = "\x1b[35m"
FgCyan = "\x1b[36m"
FgWhite = "\x1b[37m"
FgGray = "\x1b[90m"

BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"
BgGray = "\x1b[100m"

source: https://coderwall.com/p/yphywg/printing-colorful-text-in-terminal-when-run-node-js-script

Raine Revere
  • 30,985
  • 5
  • 40
  • 52
Lukas Liesis
  • 24,652
  • 10
  • 111
  • 109
7

This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here's some python code from the blender build scripts:

// This is a object for use ANSI escape to color the text in the terminal
const bColors = {
    HEADER    : '\033[95m',
    OKBLUE    : '\033[94m',
    OKGREEN   : '\033[92m',
    WARNING   : '\033[93m',
    FAIL      : '\033[91m',
    ENDC      : '\033[0m', 
    BOLD      : '\033[1m',   
    UNDERLINE : '\033[4m'
}

To use code like this, you can do something like

console.log(`${bColors.WARNING} My name is sami ${bColors.ENDC}`)
Sami
  • 115
  • 1
  • 3
6

logger/index.js

const colors = {
    Reset : "\x1b[0m",
    Bright : "\x1b[1m",
    Dim : "\x1b[2m",
    Underscore : "\x1b[4m",
    Blink : "\x1b[5m",
    Reverse : "\x1b[7m",
    Hidden : "\x1b[8m",

    FgBlack : "\x1b[30m",
    FgRed : "\x1b[31m",
    FgGreen : "\x1b[32m",
    FgYellow : "\x1b[33m",
    FgBlue : "\x1b[34m",
    FgMagenta : "\x1b[35m",
    FgCyan : "\x1b[36m",
    FgWhite : "\x1b[37m",

    BgBlack : "\x1b[40m",
    BgRed : "\x1b[41m",
    BgGreen : "\x1b[42m",
    BgYellow : "\x1b[43m",
    BgBlue : "\x1b[44m",
    BgMagenta : "\x1b[45m",
    BgCyan : "\x1b[46m",
    BgWhite : "\x1b[47m",
};

module.exports = () => {
    Object.keys(colors).forEach(key => {
        console['log' + key] = (strg) => {
            if(typeof strg === 'object') strg = JSON.stringify(strg, null, 4);
            return console.log(colors[key]+strg+'\x1b[0m');
        }
    });
}

app.js

require('./logger')();

Then use it like:

console.logBgGreen(" grüner Hintergrund ")
Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
Daniel
  • 61
  • 1
  • 1
6
var colorSet = {
    Reset: "\x1b[0m",
    Red: "\x1b[31m",
    Green: "\x1b[32m",
    Yellow: "\x1b[33m",
    Blue: "\x1b[34m",
    Magenta: "\x1b[35m"
};

var funcNames = ["info", "log", "warn", "error"];
var colors = [colorSet.Green, colorSet.Blue, colorSet.Yellow, colorSet.Red];

for (var i = 0; i < funcNames.length; i++) {
    let funcName = funcNames[i];
    let color = colors[i];
    let oldFunc = console[funcName];
    console[funcName] = function () {
        var args = Array.prototype.slice.call(arguments);
        if (args.length) {
            args = [color + args[0]].concat(args.slice(1), colorSet.Reset);
        }
        oldFunc.apply(null, args);
    };
}

// Test:
console.info("Info is green.");
console.log("Log is blue.");
console.warn("Warn is orange.");
console.error("Error is red.");
console.info("--------------------");
console.info("Formatting works as well. The number = %d", 123);
Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
Serg
  • 6,742
  • 4
  • 36
  • 54
4

Coolors

It's pretty good for use or extend. You can use simply:

var coolors = require('coolors');
console.log(coolors('My cool console log', 'red'));

Or with config:

var coolors = require('coolors');
console.log(coolors('My cool console log', {
   text: 'yellow',
   background: 'red',
   bold: true,
   underline: true,
   inverse: true,
   strikethrough: true
}));

And seems really funny to extend:

var coolors = require('coolors');
function rainbowLog(msg){
    var colorsText = coolors.availableStyles().text;
    var rainbowColors = colorsText.splice(3);
    var lengthRainbowColors = rainbowColors.length;
    var msgInLetters = msg.split('');
    var rainbowEndText = '';
    var i = 0;
    msgInLetters.forEach(function(letter){
        if(letter != ' '){
            if(i === lengthRainbowColors) i = 0;
            rainbowEndText += coolors(letter, rainbowColors[i]);
            i++;
        }else{
            rainbowEndText += ' ';
        }
    });
    return rainbowEndText;
}
coolors.addPlugin('rainbow', rainbowLog);
console.log(coolorsExtended('This its a creative example extending core with a cool rainbown style', 'rainbown'));

View Coolors module

Community
  • 1
  • 1
user1710825
  • 578
  • 5
  • 15
4

You can also use colorworks.

Usage:

var cw = require('colorworks').create();
console.info(cw.compile('[[red|Red message with a [[yellow|yellow]] word.]]'));

To make life easier, you can also make a function with it.

function say(msg) {
  console.info(cw.compile(msg));
}

Now you can do:

say(`[[yellow|Time spent: [[green|${time}]]ms.]]`);
Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
SCLeo
  • 353
  • 3
  • 14
4

I created my own module, StyleMe. I made it so I can do much with little typing. Example:

var StyleMe = require('styleme');
StyleMe.extend() // extend the string prototype

console.log("gre{Hello} blu{world}!".styleMe()) // Logs hello world! with 'hello' being green, and 'world' being blue with '!' being normal.

It can also be nested:

console.log("This is normal red{this is red blu{this is blue} back to red}".styleMe())

Or, if you dont want to extend the string prototype, you can just any of the 3 other options:

console.log(styleme.red("a string"))
console.log("Hello, this is yellow text".yellow().end())
console.log(styleme.style("some text","red,bbl"))
Andrew
  • 300
  • 2
  • 9
4

I've made a file in my snippets directory called styles.js, and I think it might help anybody who wants to import a single file.

It's a small modification to the styles.js file of color.js and has helped me a lot.

Here's the file's contents:

// Original: https://github.com/Marak/colors.js/blob/master/lib/styles.js

const styleCodes = {
    // Reset all styles.
    reset: [0, 0],
    
    // Text styles.
    bold: [1, 22],
    dim: [2, 22],
    italic: [3, 23],
    underline: [4, 24],
    inverse: [7, 27],
    hidden: [8, 28],
    strikethrough: [9, 29],
    
    // Foregound classic colours.
    fgBlack: [30, 39],
    fgRed: [31, 39],
    fgGreen: [32, 39],
    fgYellow: [33, 39],
    fgBlue: [34, 39],
    fgMagenta: [35, 39],
    fgCyan: [36, 39],
    fgWhite: [37, 39],
    fgGray: [90, 39],
    
    // Foreground bright colours.
    fgBrightRed: [91, 39],
    fgBrightGreen: [92, 39],
    fgBrightYellow: [93, 39],
    fgBrightBlue: [94, 39],
    fgBrightMagenta: [95, 39],
    fgBrightCyan: [96, 39],
    fgBrightWhite: [97, 39],

    // Background basic colours.
    bgBlack: [40, 49],
    bgRed: [41, 49],
    bgGreen: [42, 49],
    bgYellow: [43, 49],
    bgBlue: [44, 49],
    bgMagenta: [45, 49],
    bgCyan: [46, 49],
    bgWhite: [47, 49],
    bgGray: [100, 49],
    bgGrey: [100, 49],
    
    // Background bright colours.
    bgBrightRed: [101, 49],
    bgBrightGreen: [102, 49],
    bgBrightYellow: [103, 49],
    bgBrightBlue: [104, 49],
    bgBrightMagenta: [105, 49],
    bgBrightCyan: [106, 49],
    bgBrightWhite: [107, 49],
};

// This object will contain the string representation for all style codes.
const styles = {};

// Loop over all the style codes and assign them to the `styles` object.
// 
// The a `styleCode` in the `styleCodes` object consists of two numbers:
// Index 0: The opening style code (In HTML this can be the opening <b> tag).
// Index 1: The closing style code (In HTML this can be the closing </b> tag).
for (let styleCode of Object.keys(styleCodes)) {
    styles[styleCode] = {
        open: `\x1B[${styleCodes[styleCode][0]}m`,
        close: `\x1B[${styleCodes[styleCode][1]}m`,
    };
}

module.exports = styles;

It's actually quite simple to use.

const styles = require("/path/to/styles.js");

// Let's say we've got an error:
const errorOpen = styles.bold.open + styles.bgRed.open + styles.fgWhite.open;
const errorClose = styles.reset.close; // Close everything
console.log(errorOpen, "ERROR", errorClose, ": Missing semicolon at line 9.");
Ed The ''Pro''
  • 875
  • 10
  • 22
3

You can create a coloring.ts file and put a set of the following functions in it.

export let bright = (input: any) => '\x1b[1m' + input + '\x1b[0m'
export let dim = (input: any) => '\x1b[2m' + input + '\x1b[0m'
export let underscore = (input: any) => '\x1b[4m' + input + '\x1b[0m'
export let blink = (input: any) => '\x1b[5m' + input + '\x1b[0m'
export let reverse = (input: any) => '\x1b[7m' + input + '\x1b[0m'
export let hidden = (input: any) => '\x1b[8m' + input + '\x1b[0m'

export let black = (input: any) => '\x1b[30m' + input + '\x1b[0m'
export let red = (input: any) => '\x1b[31m' + input + '\x1b[0m'
export let green = (input: any) => '\x1b[32m' + input + '\x1b[0m'
export let yellow = (input: any) => '\x1b[33m' + input + '\x1b[0m'
export let blue = (input: any) => '\x1b[34m' + input + '\x1b[0m'
export let magenta = (input: any) => '\x1b[35m' + input + '\x1b[0m'
export let cyan = (input: any) => '\x1b[36m' + input + '\x1b[0m'
export let white = (input: any) => '\x1b[37m' + input + '\x1b[0m'
export let gray = (input: any) => '\x1b[90m' + input + '\x1b[0m'

export let bgBlack = (input: any) => '\x1b[40m' + input + '\x1b[0m'
export let bgRed = (input: any) => '\x1b[41m' + input + '\x1b[0m'
export let bgGreen = (input: any) => '\x1b[42m' + input + '\x1b[0m'
export let bgYellow = (input: any) => '\x1b[43m' + input + '\x1b[0m'
export let bgBlue = (input: any) => '\x1b[44m' + input + '\x1b[0m'
export let bgMagenta = (input: any) => '\x1b[45m' + input + '\x1b[0m'
export let bgCyan = (input: any) => '\x1b[46m' + input + '\x1b[0m'
export let bgWhite = (input: any) => '\x1b[47m' + input + '\x1b[0m'
export let bgGray = (input: any) => '\x1b[100m' + input + '\x1b[0m'

Then you can use them as follows:

console.log(`${blue('42')}:${yellow('00')}:${magenta('07')}`)

coloring example

3

2023

You can use modern powerful node.js lib ansis.

Using ansis you can colorize the text in the console output very simply:

// ESM
import ansis from 'ansis';
import { red, black, inverse, reset } from 'ansis/colors';

console.log(ansis.green`Hello ${inverse`ANSI`} World!`);
console.log(black.bgYellow`Warning:${reset.cyan` /path/to/file.js`} ${red`not found!`}`);

Output:

enter image description here

biodiscus
  • 365
  • 3
  • 8
2

2017:

Simple way, adding time color to the message, you don't need to change your code, use keep your console.log('msg') or console.err('error')

var clc = require("cli-color");
var mapping = {
  log: clc.blue,
  warn: clc.yellow,
  error: clc.red
};

["log", "warn", "error"].forEach(function(method) {
  var oldMethod = console[method].bind(console);
  console[method] = function() {
    oldMethod.apply(
      console,
      [mapping[method](new Date().toISOString())]
      .concat(arguments)
    );
  };
});

enter image description here

Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
stackdave
  • 6,655
  • 9
  • 37
  • 56
1

If you are using Windows CMD then go to the terminal Properties/Colors (CMD top left) and then redefine the RGB value of the offensive color. In my case I believe it's the fifth color square from the left, which I changed to (222,222,222). It does not matter if the currently selected radio button shows Screen Text or Screen Background as you just redefine that specific "system" color. Once you changed the color don't forget to select back the preferred color for the background or text before clicking OK.

After the change all these reddish messages from Node (Ember in my case) are clearly visible.

mp31415
  • 6,531
  • 1
  • 44
  • 34
1

In ubuntu you can simply use color codes:

var sys = require('sys');
process.stdout.write("x1B[31m" + your_message_in_red + "\x1B[0m\r\n");
1

node-colorify

Provides functions to print texts in color and also to do text formatting such as bold, blink, etc..

raghu
  • 92
  • 1
  • 2
  • 3
    While the link you provided may answer the question. It is best to put the essential parts of your solution directly in your answer in case the page at the link expires in the future. – Kmeixner May 31 '16 at 18:53
1
var to_rgb = function (_text, _r, _g, _b) {
    return "\x1b[38;2;" + _r + ";" + _g + ";" + _b + "m" + _text + "\x1b[0m";
};

This code help set foreground color: \x1b[38;2;R;G;Bm

This may not work some places

Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
PhamCyber
  • 21
  • 1
1

I really liked @Daniel's answer, but the console.log{color} functions didn't work the same way as regular console.log. I have made a few changes, and now all parameters to the new functions will be passed to console.log (as well as the color codes).

const _colors = {
    Reset : "\x1b[0m",
    Bright : "\x1b[1m",
    Dim : "\x1b[2m",
    Underscore : "\x1b[4m",
    Blink : "\x1b[5m",
    Reverse : "\x1b[7m",
    Hidden : "\x1b[8m",

    FgBlack : "\x1b[30m",
    FgRed : "\x1b[31m",
    FgGreen : "\x1b[32m",
    FgYellow : "\x1b[33m",
    FgBlue : "\x1b[34m",
    FgMagenta : "\x1b[35m",
    FgCyan : "\x1b[36m",
    FgWhite : "\x1b[37m",

    BgBlack : "\x1b[40m",
    BgRed : "\x1b[41m",
    BgGreen : "\x1b[42m",
    BgYellow : "\x1b[43m",
    BgBlue : "\x1b[44m",
    BgMagenta : "\x1b[45m",
    BgCyan : "\x1b[46m",
    BgWhite : "\x1b[47m",
};

const enableColorLogging = function(){
    Object.keys(_colors).forEach(key => {
        console['log' + key] = function(){
            return console.log(_colors[key], ...arguments, _colors.Reset);
        }
    });
}
J. Fortman
  • 33
  • 7
1

Minimal aliases:

{
  const f = (color) => (...args) => {
    for (const x of [color, ...args, "\33[0m"]) console.log(x);
  };

  Object.assign(console, {
    black: f("\33[30m"),
    red: f("\33[31m"),
    green: f("\33[32m"),
    yellow: f("\33[33m"),
    blue: f("\33[34m"),
    magenta: f("\33[35m"),
    cyan: f("\33[36m"),
    white: f("\33[37m"),
  });
}

// Usage
console.blue("Blue world");
catwith
  • 875
  • 10
  • 13
0

This is an approach for Windows 10 (maybe for 7) and it changes the color scheme (theme) for cmd, npm terminal itself, not only console output for a particular app.

I found the working Windows plugin - Color Tool, which is presumably developed under Windows umbrella. A description is available at the link.

I added colortool directory into system environment path variable and now it is available whenever I start terminal (NodeJs command prompt, cmd).

Roman
  • 19,236
  • 15
  • 93
  • 97
0

This works for the (I know of) Node console.

The package is shortcuts, and you can install it with this command. const short = require('@testgrandma/shortcuts');

There is two commands you can do to change the color. It's RGB color and Hex color short.colorRGB(r,g,b);

short.colorhex(hex);

You can do console.log(short.colorhex('d50000') + 'This is red!');

The package can be found here.

https://www.npmjs.com/package/@testgrandma/shortcuts

Bugs Bunny
  • 47
  • 5
0

Inline typescript solution

export const color = (function (colors) {
    const fn = (code: number, str: string) => `\x1b[${code}m${str}\x1b[39m`;
    const obj = { grey: fn.bind(null, 90) };
    for (let i = 0; i < colors.length; i++) obj[colors[i]] = fn.bind(null, 30 + i);
    return obj as { [K in typeof colors[any] | 'grey']: (str: string) => string };
})(['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'] as const);

enter image description here

pushkine
  • 177
  • 2
  • 5
0

An alternative to all this is to use a simple ANSI code generator.

  • You don't need to install packages
  • No need to search color codes, just click the button

GIF DEMO

You can use it at https://console-colors.vercel.app/

Public repository: https://github.com/alecshoppe/console-colors