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)
它将使用字符串替换并输出正确着色的红色和洋红色:
现在我想要做的是让函数接受带有替换文字的文本作为第一个参数和可变数量的参数,然后应该:
console.log()一样);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))但它似乎没有产生我想要的。
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)
| 归档时间: |
|
| 查看次数: |
250 次 |
| 最近记录: |