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(chalk.blue('Hello world!')); // Displays string in Red

A more detailed example.

const chalk = require('chalk');
 
const log = console.log;
 
// Combine styled and normal strings
log(chalk.blue('Hello') + ' World' + chalk.red('!'));
 
// Compose multiple styles using the chainable API
log(chalk.blue.bgYellow.bold('Hello world!'));
 
// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
 
// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
 
// Nest styles of the same type even (color, underline, background)
log(chalk.green(
    'I am a green line ' +
    chalk.blue.underline.bold('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');
 
console.log(error('Error!'));
console.log(warning('Warning!'));
console.log(success('Done!'));

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

console.log(chalk.red.bold.underline('Hello', 'world'));

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

Leave a Reply

Your email address will not be published. Required fields are marked *