首页 > 解决方案 > 在节点脚本中包含“无颜色”选项?

问题描述

我制作了一个节点脚本,并通过在我的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选项以使其正确打印为默认颜色?

标签: javascriptnode.js

解决方案


您可以使用%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`);

推荐阅读