在 console.log() 中替换和着色参数

kay*_*nce 2 javascript node.js chalk

有一个很好的Node.js调用模块,chalk它允许将颜色和文本格式应用于console.log()函数。

如果我写这样的东西:

console.log("test string substitution with coloring: %s, %s", chalk.red("red"), chalk.magenta("magenta"));    
Run Code Online (Sandbox Code Playgroud)

它将使用字符串替换并输出正确着色的红色和洋红色:

在此处输入图片说明

现在我想要做的是让函数接受带有替换文字的文本作为第一个参数和可变数量的参数,然后应该:

  1. substitude 对应的替换文字(就像常规的console.log()一样);
  2. 每个传递的参数都应使用红色着色chalk.red()

例如:

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

log("This must be %s, and %s as well", "red", "this must be red");
Run Code Online (Sandbox Code Playgroud)

这将给出:

例子

我试过使用,console.log(text, chalk.red.apply(null, args))但它似乎没有产生我想要的。

Mar*_*yer 5

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)));    
Run Code Online (Sandbox Code Playgroud)

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

function log(text, ...args){
    console.log(text,  ...args.map(t => chalk.red(t)));    
}
Run Code Online (Sandbox Code Playgroud)