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:
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:
console.log()
does);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:
I have tried to use console.log(text, chalk.red.apply(null, args))
but it doesn't seems to produce what I want.
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)));
}