Can't get color output in Node

Viewed 2004

I'm trying to log to the console in different colors using chalk but I haven't gotten it to work. I have a file that consists of the following two lines and I'm running it with the command node test.js

var chalk = require('chalk');
console.log(chalk.red('Hello'));
// outputs 'hello' in black

The following command does output in red so I know that it's possible in my terminal.

node <<< "console.log('\x1b[31mhello\x1b[m')"

I have "chalk": "^2.1.0" in my dev dependencies and have run a npm install. The following shows some of my setup.

$ node --version
v8.2.1

$ echo $TERM
xterm-256color

$ echo $SHELL
/bin/bash

$ echo $TERM_PROGRAM
Apple_Terminal

Any ideas?


Additionally:

It looks like chalk isn't outputting the ansi codes at all for some reason...

console.log(util.inspect('hello'));
//'hello'
console.log(util.inspect(chalk.red('hello')));
// 'hello'
console.log(util.inspect('\x1b[31mhello\x1b[m'));
// '\u001b[31mhello\u001b[m'
4 Answers

I was having a very similar issue. This answer is for anyone else in the future.

Turns out that chalk won't apply styles if you are piping the output somewhere.

In my npm scripts, I was using:

node export.js | tee export.log

Since I was switching to use Winston for logging anyway, and it can output to different files via 'transports', I no longer need the output piped somewhere and chalk is free to work.

Hope this helps someone!

In my case, it works locally. But it doesn't work on the CICD pipeline.

The solution is to set the following environment variable of your CICD pipeline:

FORCE_COLOR=1

Try this version

npm install chalk@4.1.2
Related