Colorful Node.js Message Logging with Chalk
As you work more and more with Node.js, you start to see the value of good logging, especially to the console. The problem you run into, however, is that constantly adding logged messages means that the most important messages can get lost in the shuffle. Info messages should look one way and app-killing errors should look another. The Node.js module to help us accomplish custom formatting of messages? Chalk!
Chalk has a very easy to follow, simple to use API. Here are a few code examples:
const chalk = require('chalk'); // style a string chalk.blue('Hello world!'); // combine styled and normal strings chalk.blue('Hello') + 'World' + chalk.red('!'); // compose multiple styles using the chainable API chalk.blue.bgRed.bold('Hello world!'); // pass in multiple arguments chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'); // nest styles chalk.red('Hello', chalk.underline.bgBlue('world') + '!');
You can chain methods like
bold onto color names, and visa versa. You can also append Chalk'd strings or add them as separate arguments. Chalk is very flexible without modifying the String prototype which is impressive.
Apparently over 5,000 projects use Chalk and I can see why! Big problems should come with big colors and lessor debugging information should be less prominent. Happy coding!