Learning Journal Node.js: printing in style

Learning Journal Node.js: printing in style

Rather than trying to read through a sea of text that all looks the same, you can use a library such as chalk to style your logs in the terminal, so that the logs are both meaningful and easier to find.

To do so, install chalk:

npm install chalk

Create a local reference to chalk by requiring it in your project file, then apply a styling to a log like so:

const chalk = require('chalk')

console.log(chalk.green('Success!')

This will produce a styled log that looks something like this:

You could also get really daring by adding additional styling such as:

const chalk = require('chalk')

console.log(chalk.green.bold.inverse('Success!')

If you want to get really fancy with your syntax, you could also replace the method call with a string template:

const chalk = require('chalk')

console.log(chalk.green.bold.inverse`Success!`)

This produces the same results as the previous code but allows for an alternative syntax pattern. I can't say that I love the alternative syntax pattern, but it's an option at least. ;)

Something that's fascinating to me here is both the chaining and dual syntax approach that this library uses. The chaining being that green chains to bold which chains to inverse. It appears that the syntax structure of these calls ultimately allows for indefinite chaining to apply as many supporting styles as you wish. In terms of dual syntax, green, bold, and inverse all act as both an object that can reference other styles, as well as a method that can be invoked using a string.

Congrats! You now have the ability to style your logs in semantic ways. Happy styling. :)