我制作了一个 Node 脚本,并通过在我的 console.logs
中使用颜色来美化其输出:
const noColorOption = args[1] === '--no-color' || args[2] === '--no-color';
const colors = {
green: noColorOption ? '' : '\x1b[32m%s\x1b[0m',
cyanRed: noColorOption ? '' : '\x1b[36m%s\x1b[91m%s\x1b[0m'
};
// ... examples of console.logs in my script ...
console.log(colors.cyanRed,
filename + '\n ',
redundantModules.join('\n '));
console.log(colors.green, `\nTotal files searched: ${totalFilesSearched}`);
但是,--no-color
选项无法按预期工作,因为 console.log
只是将空字符串打印为空格。
我应该添加新的 console.logs
而不带第一个参数,还是有办法分配 --no-color
选项以使其正确打印出来使用默认颜色?
最佳答案
您可以使用%s
代替空字符串。
const noColorOption = process.argv[2] === '--no-color';
const colors = {
green: noColorOption ? '%s' : '\x1b[32m%s\x1b[0m',
cyanRed: noColorOption ? '%s' : '\x1b[36m%s\x1b[91m%s\x1b[0m'
};
console.log(colors.cyanRed, __filename + '\n ');
console.log(colors.green, `Total files searched: 0`);
关于javascript - 在 Node 脚本中包含 "no-color"选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50594906/