3

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'
spencer.sm
  • 19,173
  • 10
  • 77
  • 88
  • For those working with Turbo, try this npm package as a chalk alternative, visit: https://www.npmjs.com/package/turbocolor/v/2.0.0 – Subham Burnwal Oct 20 '21 at 05:37

4 Answers4

1

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!

coblr
  • 3,008
  • 3
  • 23
  • 31
1

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

user1917528
  • 301
  • 3
  • 9
0

Uninstalling and reinstalling the package fixed the problem.

npm remove -D chalk 

npm i -D chalk
spencer.sm
  • 19,173
  • 10
  • 77
  • 88
0

Try this version

npm install chalk@4.1.2
Nishan B
  • 627
  • 7
  • 11