Styling terminal string in NodeJS

Most terminal applications or tools in NodeJS are single colored in nature. ‘Chalk’ is a nodejs package that allows you to style your application terminal output strings in various colors and styles, making it more readable and colorful.

Installation is via npm.

npm install chalk

Usage is short and simple.

const chalk = require('chalk');
console.log('Hello world!')); // Displays string in Red

A more detailed example.

const chalk = require('chalk');
const log = console.log;
// Combine styled and normal strings
log('Hello') + ' World' +'!'));
// Compose multiple styles using the chainable API
log('Hello world!'));
// Pass in multiple arguments
log('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
// Nest styles
log('Hello', chalk.underline.bgBlue('world') + '!'));
// Nest styles of the same type even (color, underline, background)
    'I am a green line ' +'with a blue substring') +
    ' that becomes green again!'

Output is shown below.

You can also easily define your own themes.

const chalk = require('chalk');
const error = chalk.keyword('red');
const warning = chalk.keyword('orange');
const success = chalk.keyword('green');

Chalk styles can be chained together, assuming the platform supports that particular style.

console.log('Hello', 'world'));

More detailed information can be found at the chalk nodejs npm.

One thought to “Styling terminal string in NodeJS”

Leave a Reply

Your email address will not be published.