【问题标题】:How to change terminal color in node.js如何在 node.js 中更改终端颜色
【发布时间】:2015-12-05 02:37:17
【问题描述】:

如何在节点 js 中设置终端字体颜色。我找到了一些模块,但颜色有限,我想使用任何颜色。

例如。 像这样。

console.log("text", "#87a213");

question 的答案是 3 个模块,但在这些模块中颜色是有限的。我需要用任何颜色打印。
谢谢。

【问题讨论】:

标签: node.js colors terminal


【解决方案1】:

你还可以使用一个超级简单的 mixin 来为字符串原型添加颜色支持:

// Node String Colors Support (https://git.io/colors)
// Usage console.log("Hello!".green())
const _c = require('util').inspect.colors;
Object.keys(_c).forEach(c =>String.prototype[c] = s =>`\x1b[${_c[c][0]}m${s}\x1b[${_c[c][1]}m`);

不依赖 util 的替代方案:(不推荐)

// Node String Colors Support. (no util version) (https://git.io/colors)
// Usage console.log("Hello!".green())
const _c = {bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};
Object.keys(_c).forEach(c =>String.prototype[c] = s =>`\x1b[${_c[c][0]}m${s}\x1b[${_c[c][1]}m`); 

全球版本,如果您不想更改字符串原型(这更安全

// Node String Colors Support. (global version) (https://git.io/colors)
// Usage console.log(green("Hello world!")
const _c = require('util').inspect.colors;
Object.keys(_c).forEach(c =>global[c] = s =>`\x1b[${_c[c][0]}m${s}\x1b[${_c[c][1]}m`);

【讨论】:

    【解决方案2】:

    您可以使用ansi-256-colors 包。但它不支持任何颜色。但它支持多种颜色。

    安装:

    npm install --save ansi-256-colors
    

    使用方法:

    console.log(colors.fg.getRgb(2,3,4) + colors.bg.getRgb(4,4,4) + 'Hello world!' + colors.reset);
    

    【讨论】:

    • 我的主要目标是读取 jpg 图像,然后将其打印到终端,所以我需要读取每个像素值,然后用这种颜色打印一个符号。这是因为我需要打印任何颜色。也许你知道更好的方法?谢谢你
    • 为每个像素打印一个字符是没有用的,因为如果图像是 800x600,那么一行将有 800 个像素。连续打印 800 个字符似乎太多了。相反,尝试将图像划分为网格并为每个单元格近似颜色(rgb 值)。然后以该颜色打印一个字符。对所有单元格执行此操作。
    【解决方案3】:

    我一直在使用包colorshttps://www.npmjs.com/package/colors,它非常容易使用,因为它扩展了String,所以对于每个字符串你都可以简单地做.red

    var colors = require('colors');
    
    console.log('hello'.green); // outputs green text 
    console.log('i like cake and pies'.underline.red) // outputs red underlined text 
    console.log('inverse the color'.inverse); // inverses the color 
    console.log('OMG Rainbows!'.rainbow); // rainbow 
    console.log('Run the trap'.trap); // Drops the bass 
    

    【讨论】:

    • 但是颜色有限,这里可以用任何颜色吗?
    猜你喜欢
    • 1970-01-01
    • 2016-08-06
    • 2023-03-18
    • 2022-01-08
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    相关资源
    最近更新 更多