1

I know some tools to change console's text color, such as chalk . But when I use throw statement to print error message and need to red it:

const chalk = require('chalk');

throw new Error(chalk.red('some error messages'));

It failed with no red color's error message:

?[31msome error messages?[39m

Is there any way to change the color of error message caused by throw statement?

wenkang lin
  • 119
  • 1
  • 10

1 Answers1

0

Are you sure your console understands ANSI sequences? I mean, the browser console may not understand them at all, and Windows command line displays them properly only in Windows 10.

Generally you should avoid throwing ANSI-colored error messages, as it may not work on every system, and thus is a bad practice. Nevertheless throw alone should not break the sequence, as it is just a string of ASCII characters.

What may break it is console itself not understanding it. What you have pasted (?[31msome error messages?[39m) differs from a valid ANSI-colored text only by replacing the escape character (ASCII code 27) with "?". Thus I suspect you are trying to display the text in a console not suitable of interpreting ANSI codes. Use Windows 10 console or any Unix/Linux/MacOS X system console and it will work. In the consoles of webbrowsers and in Windows versions prior to 10 it won't.

If you need colored console output in webbrowser see this answer.

jaboja
  • 1,792
  • 1
  • 19
  • 32