Search code examples
javascriptnode.jschalk

Substitute and colorize arguments in console.log()


There's a nice module for Node.js called chalk that allows to apply coloring and text formatting to console.log() function.

If I write something like this:

console.log("test string substitution with coloring: %s, %s", chalk.red("red"), chalk.magenta("magenta"));    

it will use string substitution and outputs red and mageenta properly colored:

enter image description here

Now what I am trying to make is to make functions that accepts text with substitution literals as first parameter and variable amount of parameters later that should:

  1. substitude corresponding substitution literals (just as regular console.log() does);
  2. each passed parameter shall be colored with red using chalk.red();

For example:

function log(text, ...args) {
   // magic here
}

log("This must be %s, and %s as well", "red", "this must be red");

This shall give this:

example

I have tried to use console.log(text, chalk.red.apply(null, args)) but it doesn't seems to produce what I want.


Solution

  • You just need to spread an array into the console.log(). For example, you can do it inline with map():

    let chalk = require('chalk')
    
    console.log("test string substitution with coloring: %s and %s",  ...["red", "this must be red"].map(t => chalk.red(t)));    
    

    Of course, you could make it a function as well:

    function log(text, ...args){
        console.log(text,  ...args.map(t => chalk.red(t)));    
    }