【问题标题】:How to change node.js's console font color?如何更改 node.js 的控制台字体颜色?
【发布时间】:2018-04-10 18:55:52
【问题描述】:

由于眼睛问题,我不得不将控制台背景颜色更改为白色,但字体是灰色的,这使得消息无法阅读。怎么改?

【问题讨论】:

  • 在你已经用来改变背景颜色的地方,你可以改变其他颜色。
  • 我遇到了同样的问题。我怀疑@Viclib 正在使用 Windows(我也是),这就是为什么更改终端颜色的指令是一个外来概念的原因。 Windows 命令提示符允许更改 2 种前景色和 2 种背景色。 Node 使用 windows 命令提示符无法定义的其他颜色。
  • @GregWoods。下面接受的答案在 Windows 中有效!
  • 我后来发现我对 Windows 命令提示符颜色如何工作的心智模型是完全错误的。我错误地假设(由于糟糕的用户界面)您只能更改前景色、背景色。这是错误的。控制台应用程序可以使用所有 16 种颜色,为所有 16 种颜色选择合理的颜色至关重要,并且始终使用颜色拼贴 1 作为背景(而拼贴 9 用于“弹出背景”)。这对我来说是一个启示,我写了一篇博客文章(确实是一个罕见的事件)。 gregwoods.co.uk/2015/04/…

标签: node.js colors console


【解决方案1】:

您可以在下面找到运行 node.js 应用程序时文本到命令的颜色参考:

console.log('\x1b[36m%s\x1b[0m', 'I am cyan');  //cyan
console.log('\x1b[33m%s\x1b[0m', stringToMakeYellow);  //yellow

注意%s 是字符串(第二个参数)被注入的位置。 \x1b[0m 重置终端颜色,使其不再是选择的颜色。

颜色参考

Reset = "\x1b[0m"
Bright = "\x1b[1m"
Dim = "\x1b[2m"
Underscore = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"

FgBlack = "\x1b[30m"
FgRed = "\x1b[31m"
FgGreen = "\x1b[32m"
FgYellow = "\x1b[33m"
FgBlue = "\x1b[34m"
FgMagenta = "\x1b[35m"
FgCyan = "\x1b[36m"
FgWhite = "\x1b[37m"

BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"

编辑:

例如,\x1b[31m 是一个转义序列,它将被您的终端拦截并指示它切换到红色。事实上,\x1b不可打印控制字符 escape 的代码。仅处理颜色和样式的转义序列也称为 ANSI escape code 并且是标准化的,因此它们(应该)适用于任何平台。

维基百科对不同终端如何显示颜色进行了很好的比较 https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

【讨论】:

  • 我接受了这个问题,因为它是最懒惰的,有很多颜色,没有依赖关系。如果您想要更简单的解决方案 with 依赖项,请查看@nelsonic 的答案,该答案建议非常简单的库。
  • 您在哪里找到此参考资料?颜色值中的每个字符是什么意思?
  • @giorgos29cm → see here。顺便说一句,为明亮的颜色添加 1;,即 "\x1b[1;34m" == 浅蓝色...
  • 打印到文件而不是控制台时,我应该如何防止这些字符显示?
  • 我接受了这个答案,并将其稍微更改为可运行代码。 stackoverflow.com/a/57100519/4808079
【解决方案2】:

有多个包可用于在 Node.js 中格式化控制台文本。最受欢迎的是:

用法:

粉笔:

const chalk = require('chalk');
console.log(chalk.red('Text in red'));

颜色:

const colors = require('colors');
console.log('Text in red'.red);

CLI-颜色:

const clc = require('cli-color');
console.log(clc.red('Text in red'));

许多人已经注意到他们不赞成colors 更改字符串原型。如果您希望自己的原型不受影响,请改用以下代码:

const colors = require('colors/safe');
console.log(colors.red('Text in red'));

【讨论】:

  • 它甚至对样式有简单的轻量级支持!
  • @devundef 同意您将方法添加到 String 对象。可能值得一提的是 GitHub 上的模块作者。和/或建议具有类似简单程度的替代模块/方法。
  • 虽然我同意 MattJohnson 的回答(覆盖 util.inpect 方法的默认颜色 - 见下文)比使用 Colors 模块更好,但 Colors 模块需要 零设置 并且适合绝大多数用户的需求,只是改变了 console.log 输出的颜色。当然,“使用内置插件”是不好的(同意 100%),但任何 deployed 代码都不应该包含 console.log 语句,所以让我们务实一点。 @devundef 添加到原型中的额外 String 方法是否会影响您的单元测试?
  • Colors 现在有:var colors = require('colors/safe'); 然后使用 colors.red('left string all alone')
  • 我认为 chalk 停止了对 nodejs 的支持!
【解决方案3】:

如果您想直接自己更改颜色而不使用模块,请尝试

console.log('\x1b[36m', 'sometext' ,'\x1b[0m');

首先\x1b[36m 将颜色更改为36,然后返回终端颜色0

Here's a list of ANSI color codes

【讨论】:

【解决方案4】:

为您的输出着色您可以使用那里的示例:
https://help.ubuntu.com/community/CustomizingBashPrompt

也是Gist for nodeJs

例如,如果您想要部分文本为红色,只需执行 console.log :

"\033[31m this will be red \033[91m and this will be normal"

基于此,我为 Node.js 创建了“colog”扩展。您可以使用以下方式安装它:

npm install colog

回购和npm: https://github.com/dariuszp/colog

【讨论】:

  • 我相信 OP 不想以特定颜色打印特定文本,但默认情况下所有终端输出都使用不同颜色,甚至在白色背景下可能是黑色。
  • \033[31m 有效,但 \033[91m 无效。对于 Ubuntu 终端,它应该是 \033[0m
  • 八进制转义似乎不起作用:error: octal escape sequences "\033[31mServer ready @ #{app.get('port')}\033[91m" are not allowed
  • \033[0m 应该用于将文本恢复正常,而不是\033[91m
  • 这将导致SyntaxError: Octal literals are not allowed in strict mode.“问题是由ANSI转义码引起的,它是一个字符串,而不是一个以0开头的数字(八进制文字),如0644。在我的情况下,字符串是'\033[0m'。解决方案是将其替换为 '\u001b[0m'" - github.com/TypeStrong/ts-node/issues/90#issue-144783379
【解决方案5】:

这是控制台中可用颜色(背景和前景)的列表以及一些可用操作(如重置、反转等)。

const colours = {
    reset: "\x1b[0m",
    bright: "\x1b[1m",
    dim: "\x1b[2m",
    underscore: "\x1b[4m",
    blink: "\x1b[5m",
    reverse: "\x1b[7m",
    hidden: "\x1b[8m",
    
    fg: {
        black: "\x1b[30m",
        red: "\x1b[31m",
        green: "\x1b[32m",
        yellow: "\x1b[33m",
        blue: "\x1b[34m",
        magenta: "\x1b[35m",
        cyan: "\x1b[36m",
        white: "\x1b[37m",
        crimson: "\x1b[38m" // Scarlet
    },
    bg: {
        black: "\x1b[40m",
        red: "\x1b[41m",
        green: "\x1b[42m",
        yellow: "\x1b[43m",
        blue: "\x1b[44m",
        magenta: "\x1b[45m",
        cyan: "\x1b[46m",
        white: "\x1b[47m",
        crimson: "\x1b[48m"
    }
};

这是一个如何使用它的示例:

console.log(colours.bg.blue, colours.fg.white, "I am a white message with a blue background", colours.reset) ; 
// Make sure that you don't forget "colours.reset" at the so that you can reset the console back to it's original colours.

或者你可以安装一些实用模块:

npm install console-info console-warn console-error --save-dev

这些模块在您使用时会在控制台显示如下内容:

【讨论】:

  • 我使用的是相同的并且工作正常,但由于某种原因,Dim 什么也没做?我想要灰色效果,所以认为使用带有暗淡效果的白色会导致灰色,但只有白色打印没有暗淡。有什么想法吗?
  • 不幸的是,在控制台中这样使用它会产生很多空间。
  • 在颜色之间使用+ 而不是, 以避免空格
  • Crimson 不会在控制台中退出!
【解决方案6】:

表情符号

您可以像其他人在回答中提到的那样为文本使用颜色。

但您可以改用表情符号!例如,您可以将⚠️ 用于警告消息,将? 用于错误消息。

或者简单地将这些笔记本用作颜色:

?: error message
?: warning message
?: ok status message
?: action message
?: canceled status message
?: Or anything you like and want to recognize immediately by color

? 奖励:

此方法还可以帮助您直接在源代码中快速扫描和查找日志。

例如:

console.log('Bring with ❤️ to you from Mojtaba Hosseini');

某些 Linux 发行版的默认表情符号字体可能默认不是彩色的,您可能希望首先让它们变得彩色。


如何打开表情选择器?

mac os: 控制 + 命令 + 空格

windows: win + .

linux: control + .control + ;

【讨论】:

  • 表情包怎么安装?
  • @yehonatanyehezkel emoji 与 unicode 一样,即只是普通字符。
  • 提示:在Win10上,您可以按[Win] + [.]打开特殊的表情符号窗口:)
【解决方案7】:

根据this documentation,您可以根据输出的数据类型更改颜色:

// you'll need the util module
var util = require('util');

// let's look at the defaults: 
util.inspect.styles

{ special: 'cyan',
  number: 'yellow',
  boolean: 'yellow',
  undefined: 'grey',
  null: 'bold',
  string: 'green',
  date: 'magenta',
  regexp: 'red' }

// what are the predefined colors?
util.inspect.colors

{ 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 ] }

这些似乎是 ANSI SGR 转义码,其中第一个数字是在输出之前发出的代码,第二个数字是在之后发出的代码。因此,如果我们查看the chart of ANSI SGR codes on Wikipedia,您会发现其中大多数以数字 30-37 开始设置前景色,并以数字 39 结束以重置为默认前景色。

所以我不喜欢的一件事是其中一些是多么黑暗。特别是日期。继续在控制台中尝试new Date()。黑色上的深洋红色真的很难阅读。让我们将其改为浅洋红色。

// first define a new color
util.inspect.colors.lightmagenta = [95,39];

// now assign it to the output for date types
util.inspect.styles.date = 'lightmagenta';

现在,当您尝试new Date() 时,输出的可读性要高得多。

如果您想在启动节点时自动设置颜色,请创建一个启动 repl 的脚本,如下所示:

// set your colors however desired
var util = require('util');
util.inspect.colors.lightmagenta = [95,39];
util.inspect.styles.date = 'lightmagenta';

// start the repl    
require('repl').start({});

保存此文件(例如,init.js),然后运行 ​​node.exe init.js。它将设置颜色并启动 node.js 命令提示符。

(感谢this answer 中的 loganfsmyth 提出的 repl 想法。)

【讨论】:

  • 这应该是公认的答案。其他带有 ansi 代码的代码只是一个 hack。
【解决方案8】:

Reset: "\x1b[0m"
Bright: "\x1b[1m"
Dim: "\x1b[2m"
Underscore: "\x1b[4m"
Blink: "\x1b[5m"
Reverse: "\x1b[7m"
Hidden: "\x1b[8m"

FgBlack: "\x1b[30m"
FgRed: "\x1b[31m"
FgGreen: "\x1b[32m"
FgYellow: "\x1b[33m"
FgBlue: "\x1b[34m"
FgMagenta: "\x1b[35m"
FgCyan: "\x1b[36m"
FgWhite: "\x1b[37m"

BgBlack: "\x1b[40m"
BgRed: "\x1b[41m"
BgGreen: "\x1b[42m"
BgYellow: "\x1b[43m"
BgBlue: "\x1b[44m"
BgMagenta: "\x1b[45m"
BgCyan: "\x1b[46m"
BgWhite: "\x1b[47m"

例如,如果您想要一个带有蓝色背景的暗红色文本,您可以在 Javascript 中这样做:

console.log("\x1b[2m", "\x1b[31m", "\x1b[44m", "Sample Text", "\x1b[0m");

颜色和效果的顺序似乎不是那么重要,但请记住在最后重置颜色和效果。

【讨论】:

  • @Sergey blink 对我也不起作用,好像它在 Node 中不可用
  • @Sv443 但它适用于屏幕截图 :) 问题是关于 Node.js 的。我认为它不仅在 Windows 控制台中有效。你用什么操作系统?
  • @Sergey 我正在使用 Windows 并在 CMD 和 Powershell 中尝试过,但都不起作用
  • @Sergey 我的截图来自 MacOS 终端应用程序。我相信这是你的 shell 应用程序应该支持的东西。如果您使用的是 Windows,我建议您尝试安装 Cygwin 并在 bash 上尝试。我也很想知道这个。
  • @Shnd 我不确定它是否相同,但我在 git-bash 上尝试过它也没有工作。
【解决方案9】:

我为没有依赖关系的 npm 脚本编写的一个方便的单行代码:

const { r, g, b, w, c, m, y, k } = [
  ['r', 1], ['g', 2], ['b', 4], ['w', 7],
  ['c', 6], ['m', 5], ['y', 3], ['k', 0],
].reduce((cols, col) => ({
  ...cols,  [col[0]]: f => `\x1b[3${col[1]}m${f}\x1b[0m`
}), {})

console.log(`${g('I')} love ${r('Italy')}`)

r,g,b,w,c,m,y,k 代表 red、green、blue、white、cyan、magenta、yellow 和 black

【讨论】:

    【解决方案10】:

    Sindre Sorhus 的这个图书馆是目前最好的:

    chalk

    • 高性能
    • 不扩展String.prototype
    • 富有表现力的 API
    • 嵌套样式的能力
    • 干净而专注
    • 自动检测颜色支持
    • 积极维护
    • 被 5500 多个模块使用

    【讨论】:

    • 是的,但它是另一个依赖项
    【解决方案11】:

    我发现上面的这个答案 (https://stackoverflow.com/a/41407246/4808079) 非常有用,但不完整。如果你只想给某样东西上色一次,我想这很好,但我认为以可运行的函数形式共享它更适用于现实生活中的用例。

    const Color = {
      Reset: "\x1b[0m",
      Bright: "\x1b[1m",
      Dim: "\x1b[2m",
      Underscore: "\x1b[4m",
      Blink: "\x1b[5m",
      Reverse: "\x1b[7m",
      Hidden: "\x1b[8m",
      
      FgBlack: "\x1b[30m",
      FgRed: "\x1b[31m",
      FgGreen: "\x1b[32m",
      FgYellow: "\x1b[33m",
      FgBlue: "\x1b[34m",
      FgMagenta: "\x1b[35m",
      FgCyan: "\x1b[36m",
      FgWhite: "\x1b[37m",
      
      BgBlack: "\x1b[40m",
      BgRed: "\x1b[41m",
      BgGreen: "\x1b[42m",
      BgYellow: "\x1b[43m",
      BgBlue: "\x1b[44m",
      BgMagenta: "\x1b[45m",
      BgCyan: "\x1b[46m",
      BgWhite: "\x1b[47m"
    }
    
    function colorString(color, string) {
      return `${color}${string}${Color.Reset}`;
    }
    
    function colorLog(color, ...args) {
      console.log(...args.map(
       (it) => typeof it === "string" ? colorString(color, string) : it
      ));
    }
    

    像这样使用它:

    colorLog(Color.FgYellow, "Some Yellow text to console log", { someObj: true });
    
    console.log([
      colorString(Color.FgRed, "red"),
      colorString(Color.FgGreen, "green"),
      colorString(Color.FgBlue, "blue"),
    ].join(", "));
    

    【讨论】:

    • 感谢您的回答!我建议允许更多 args 到 console.log 函数 colorStringLog(color, string, ...args) { console.log(colorString(color, string), ...args) }
    • 随意编辑答案并添加...args。这绝对是更正确的方法。虽然应该确保对象没有被字符串化。
    【解决方案12】:

    对于colors 的流行替代方案,它不会与字符串对象的内置方法混淆,我建议查看cli-color

    包括颜色和可链接的样式,例如粗体、斜体和下划线。

    有关此类别中各种模块的比较,请参阅here

    【讨论】:

      【解决方案13】:

      没有库,没有复杂,只是简单:

      console.log(red('Error!'));
      
      function red(s) {
          return '\033[31m' + s;
      }
      

      【讨论】:

      • 当您发现它不能以控制台处理对象的方式处理对象,并且它不尊重控制台流类型或 TTY 支持时,这并不简单,这会产生更多问题.这只是一个 hack,会带来很多问题。
      • 这就是 JSON.stringify 的用途
      • @wayofthefuture “它不适用于控制台处理对象的方式”意味着我们可以展开和折叠对象。
      【解决方案14】:

      我重载了控制台方法。

      var colors={
      Reset: "\x1b[0m",
      Red: "\x1b[31m",
      Green: "\x1b[32m",
      Yellow: "\x1b[33m"
      };
      
      var infoLog = console.info;
      var logLog = console.log;
      var errorLog = console.error;
      var warnLog = console.warn;
      
      console.info= function(args)
      {
          var copyArgs = Array.prototype.slice.call(arguments);
          copyArgs.unshift(colors.Green);
          copyArgs.push(colors.Reset);
          infoLog.apply(null,copyArgs);
      };
      
      console.warn= function(args)
      {
          var copyArgs = Array.prototype.slice.call(arguments);
          copyArgs.unshift(colors.Yellow);
          copyArgs.push(colors.Reset);
          warnLog.apply(null,copyArgs);
      };
      console.error= function(args)
      {
          var copyArgs = Array.prototype.slice.call(arguments);
          copyArgs.unshift(colors.Red);
          copyArgs.push(colors.Reset);
          errorLog.apply(null,copyArgs);
      };
      
      // examples
      console.info("Numeros",1,2,3);
      console.warn("pares",2,4,6);
      console.error("reiniciandooo");
      

      输出是。

      【讨论】:

      • 这不适用于格式化语法。示例:console.info('Hello %s', 'World!') 应该显示 Hello World!,而不是 Hello %s World!
      • @vitaly-t 试试 this:应该可以。
      【解决方案15】:

      目前有两种方法可以查看更改 Node.js 控制台的颜色。

      一种是通过通用库,可以用颜色标签装饰文本字符串,然后通过标准console.log 输出。

      今天的顶级库:

      另一种方式 - 修补现有的控制台方法。一个这样的库 - manakin 可让您自动为所有控制台方法(logwarnerrorinfo)设置标准颜色。

      与通用颜色库的一个显着区别 - 它可以全局或本地设置颜色,同时为每个 Node.js 控制台方法保持一致的语法和输出格式,然后您无需指定颜色即可使用它们,因为它们是全部自动设置。

      由于眼睛问题,我不得不将控制台背景颜色更改为白色,但字体是灰色的,这使得消息无法阅读。怎么改?

      专门针对您的问题,这是最简单的解决方案:

      var con = require('manakin').global;
      con.log.color = 30; // Use black color for console.log
      

      它将为您的应用程序中的每个console.log 调用设置黑色。见more color codes

      manakin 使用的默认颜色:

      【讨论】:

        【解决方案16】:

        paint-console

        简单的可着色日志。支持检查对象和单行更新 这个包只是重绘控制台。

        安装

        npm install paint-console
        

        用法

        require('paint-console');
        
        console.info('console.info();');
        console.warn('console.warn();');
        console.error('console.error();');
        console.log('console.log();');
        

        demo

        【讨论】:

        • 正是我需要的基本脚本。谢谢
        【解决方案17】:

        遇到了这个问题,想在标准输出上使用一些颜色而不需要任何依赖。这结合了这里的其他一些很好的答案。

        这就是我所拥有的。 (需要节点 v4 或更高版本)

        // colors.js
        const util = require('util')
        
        function colorize (color, text) {
          const codes = util.inspect.colors[color]
          return `\x1b[${codes[0]}m${text}\x1b[${codes[1]}m`
        }
        
        function colors () {
          let returnValue = {}
          Object.keys(util.inspect.colors).forEach((color) => {
            returnValue[color] = (text) => colorize(color, text)
          })
          return returnValue
        }
        
        module.exports = colors()
        

        只需要文件,然后像这样使用它:

        const colors = require('./colors')
        console.log(colors.green("I'm green!"))
        

        预定义的颜色代码可用here

        【讨论】:

        • 例如,在重定向到日志文件时将无法正常工作。
        【解决方案18】:

        我不希望对此有任何依赖,只有这些在 OS X 上对我有用。此处答案中的所有其他示例都给了我Octal literal 错误。

        Reset = "\x1b[0m"
        Bright = "\x1b[1m"
        Dim = "\x1b[2m"
        Underscore = "\x1b[4m"
        Blink = "\x1b[5m"
        Reverse = "\x1b[7m"
        Hidden = "\x1b[8m"
        
        FgBlack = "\x1b[30m"
        FgRed = "\x1b[31m"
        FgGreen = "\x1b[32m"
        FgYellow = "\x1b[33m"
        FgBlue = "\x1b[34m"
        FgMagenta = "\x1b[35m"
        FgCyan = "\x1b[36m"
        FgWhite = "\x1b[37m"
        
        BgBlack = "\x1b[40m"
        BgRed = "\x1b[41m"
        BgGreen = "\x1b[42m"
        BgYellow = "\x1b[43m"
        BgBlue = "\x1b[44m"
        BgMagenta = "\x1b[45m"
        BgCyan = "\x1b[46m"
        BgWhite = "\x1b[47m"
        

        来源:https://coderwall.com/p/yphywg/printing-colorful-text-in-terminal-when-run-node-js-script

        【讨论】:

          【解决方案19】:
          var colorSet = {
              Reset: "\x1b[0m",
              Red: "\x1b[31m",
              Green: "\x1b[32m",
              Yellow: "\x1b[33m",
              Blue: "\x1b[34m",
              Magenta: "\x1b[35m"
          };
          
          var funcNames = ["info", "log", "warn", "error"];
          var colors = [colorSet.Green, colorSet.Blue, colorSet.Yellow, colorSet.Red];
          
          for (var i = 0; i < funcNames.length; i++) {
              let funcName = funcNames[i];
              let color = colors[i];
              let oldFunc = console[funcName];
              console[funcName] = function () {
                  var args = Array.prototype.slice.call(arguments);
                  if (args.length) {
                      args = [color + args[0]].concat(args.slice(1), colorSet.Reset);
                  }
                  oldFunc.apply(null, args);
              };
          }
          
          // Test:
          console.info("Info is green.");
          console.log("Log is blue.");
          console.warn("Warn is orange.");
          console.error("Error is red.");
          console.info("--------------------");
          console.info("Formatting works as well. The number = %d", 123);
          

          【讨论】:

            【解决方案20】:

            logger/index.js

            const colors = {
                Reset : "\x1b[0m",
                Bright : "\x1b[1m",
                Dim : "\x1b[2m",
                Underscore : "\x1b[4m",
                Blink : "\x1b[5m",
                Reverse : "\x1b[7m",
                Hidden : "\x1b[8m",
            
                FgBlack : "\x1b[30m",
                FgRed : "\x1b[31m",
                FgGreen : "\x1b[32m",
                FgYellow : "\x1b[33m",
                FgBlue : "\x1b[34m",
                FgMagenta : "\x1b[35m",
                FgCyan : "\x1b[36m",
                FgWhite : "\x1b[37m",
            
                BgBlack : "\x1b[40m",
                BgRed : "\x1b[41m",
                BgGreen : "\x1b[42m",
                BgYellow : "\x1b[43m",
                BgBlue : "\x1b[44m",
                BgMagenta : "\x1b[45m",
                BgCyan : "\x1b[46m",
                BgWhite : "\x1b[47m",
            };
            
            module.exports = () => {
                Object.keys(colors).forEach(key => {
                    console['log' + key] = (strg) => {
                        if(typeof strg === 'object') strg = JSON.stringify(strg, null, 4);
                        return console.log(colors[key]+strg+'\x1b[0m');
                    }
                });
            }
            

            app.js

            require('./logger')();
            

            然后像这样使用它:

            console.logBgGreen(" grüner Hintergrund ")
            

            【讨论】:

              【解决方案21】:

              这在某种程度上取决于您使用的平台。最常见的方式 要做到这一点是通过打印 ANSI 转义序列。举个简单的例子, 这是搅拌机构建脚本中的一些 python 代码:

              // This is a object for use ANSI escape to color the text in the terminal
              const bColors = {
                  HEADER    : '\033[95m',
                  OKBLUE    : '\033[94m',
                  OKGREEN   : '\033[92m',
                  WARNING   : '\033[93m',
                  FAIL      : '\033[91m',
                  ENDC      : '\033[0m', 
                  BOLD      : '\033[1m',   
                  UNDERLINE : '\033[4m'
              }
              

              要使用这样的代码,你可以这样做

              console.log(`${bColors.WARNING} My name is sami ${bColors.ENDC}`)
              

              【讨论】:

              【解决方案22】:

              如果您想保持简单而不使用任何外部模块/学习新的 API/破解核心 console 函数:

              const LCERROR = '\x1b[31m%s\x1b[0m'; //red
              const LCWARN = '\x1b[33m%s\x1b[0m'; //yellow
              const LCINFO = '\x1b[36m%s\x1b[0m'; //cyan
              const LCSUCCESS = '\x1b[32m%s\x1b[0m'; //green
              
              const logger = class {
                static error(message, ...optionalParams) { console.error(LCERROR, message, ...optionalParams) }
                static warn(message, ...optionalParams) { console.warn(LCWARN, message, ...optionalParams) }
                static info(message, ...optionalParams) { console.info(LCINFO, message, ...optionalParams) }
                static success(message, ...optionalParams) { console.info(LCSUCCESS, message, ...optionalParams) }
              }
              
              // then instead (as presented in the accepted answer)
              // console.error(LCERROR, 'Error message in red.');
              // you write:
              
              logger.error('Error message in red.');
              
              // or with multiple parameters (only the message will be red):
              
              logger.error('Error message in red.', 1, false, null, {someKey: 'whatever'});
              
              // or use backticks (template literal) instead multiple params:
              
              logger.error(`This will be red as ${foo} and ${bar} too.`);
              

              现在您可以像使用console 一样使用您的logger。没有要记住的新 API... 通常您会将其放入模块 (logger.js) 中并导出 class 以便能够在您的应用程序中的任何地方使用它作为 const logger = require('./logger');

              【讨论】:

                【解决方案23】:

                Coolors

                它非常适合使用或扩展。您可以简单地使用:

                var coolors = require('coolors');
                console.log(coolors('My cool console log', 'red'));
                

                或者使用配置:

                var coolors = require('coolors');
                console.log(coolors('My cool console log', {
                   text: 'yellow',
                   background: 'red',
                   bold: true,
                   underline: true,
                   inverse: true,
                   strikethrough: true
                }));
                

                而且扩展起来似乎真的很有趣:

                var coolors = require('coolors');
                function rainbowLog(msg){
                    var colorsText = coolors.availableStyles().text;
                    var rainbowColors = colorsText.splice(3);
                    var lengthRainbowColors = rainbowColors.length;
                    var msgInLetters = msg.split('');
                    var rainbowEndText = '';
                    var i = 0;
                    msgInLetters.forEach(function(letter){
                        if(letter != ' '){
                            if(i === lengthRainbowColors) i = 0;
                            rainbowEndText += coolors(letter, rainbowColors[i]);
                            i++;
                        }else{
                            rainbowEndText += ' ';
                        }
                    });
                    return rainbowEndText;
                }
                coolors.addPlugin('rainbow', rainbowLog);
                console.log(coolorsExtended('This its a creative example extending core with a cool rainbown style', 'rainbown'));
                

                View Coolors module

                【讨论】:

                • 例如,当重定向到日志文件时,这将无法在 Node.js 中正确工作。
                【解决方案24】:

                我创建了自己的模块StyleMe。我做到了,所以我可以用很少的打字做很多事情。示例:

                var StyleMe = require('styleme');
                StyleMe.extend() // extend the string prototype
                
                console.log("gre{Hello} blu{world}!".styleMe()) // Logs hello world! with 'hello' being green, and 'world' being blue with '!' being normal.
                

                也可以嵌套:

                console.log("This is normal red{this is red blu{this is blue} back to red}".styleMe())
                

                或者,如果您不想扩展字符串原型,您可以选择其他 3 个选项中的任何一个:

                console.log(styleme.red("a string"))
                console.log("Hello, this is yellow text".yellow().end())
                console.log(styleme.style("some text","red,bbl"))
                

                【讨论】:

                  【解决方案25】:

                  您也可以使用colorworks

                  用法:

                  var cw = require('colorworks').create();
                  console.info(cw.compile('[[red|Red message with a [[yellow|yellow]] word.]]'));
                  

                  为了让生活更轻松,你也可以用它做一个函数。

                  function say(msg) {
                    console.info(cw.compile(msg));
                  }
                  

                  现在你可以这样做了:

                  say(`[[yellow|Time spent: [[green|${time}]]ms.]]`);
                  

                  【讨论】:

                    【解决方案26】:

                    我在我的 sn-ps 目录中创建了一个名为 styles.js 的文件,我认为它可能对任何想要导入单​​个文件的人有所帮助。

                    这是对styles.js file of color.js 的一个小修改,对我帮助很大。

                    这是文件的内容:

                    // Original: https://github.com/Marak/colors.js/blob/master/lib/styles.js
                    
                    const styleCodes = {
                        // Reset all styles.
                        reset: [0, 0],
                        
                        // Text styles.
                        bold: [1, 22],
                        dim: [2, 22],
                        italic: [3, 23],
                        underline: [4, 24],
                        inverse: [7, 27],
                        hidden: [8, 28],
                        strikethrough: [9, 29],
                        
                        // Foregound classic colours.
                        fgBlack: [30, 39],
                        fgRed: [31, 39],
                        fgGreen: [32, 39],
                        fgYellow: [33, 39],
                        fgBlue: [34, 39],
                        fgMagenta: [35, 39],
                        fgCyan: [36, 39],
                        fgWhite: [37, 39],
                        fgGray: [90, 39],
                        
                        // Foreground bright colours.
                        fgBrightRed: [91, 39],
                        fgBrightGreen: [92, 39],
                        fgBrightYellow: [93, 39],
                        fgBrightBlue: [94, 39],
                        fgBrightMagenta: [95, 39],
                        fgBrightCyan: [96, 39],
                        fgBrightWhite: [97, 39],
                    
                        // Background basic colours.
                        bgBlack: [40, 49],
                        bgRed: [41, 49],
                        bgGreen: [42, 49],
                        bgYellow: [43, 49],
                        bgBlue: [44, 49],
                        bgMagenta: [45, 49],
                        bgCyan: [46, 49],
                        bgWhite: [47, 49],
                        bgGray: [100, 49],
                        bgGrey: [100, 49],
                        
                        // Background bright colours.
                        bgBrightRed: [101, 49],
                        bgBrightGreen: [102, 49],
                        bgBrightYellow: [103, 49],
                        bgBrightBlue: [104, 49],
                        bgBrightMagenta: [105, 49],
                        bgBrightCyan: [106, 49],
                        bgBrightWhite: [107, 49],
                    };
                    
                    // This object will contain the string representation for all style codes.
                    const styles = {};
                    
                    // Loop over all the style codes and assign them to the `styles` object.
                    // 
                    // The a `styleCode` in the `styleCodes` object consists of two numbers:
                    // Index 0: The opening style code (In HTML this can be the opening <b> tag).
                    // Index 1: The closing style code (In HTML this can be the closing </b> tag).
                    for (let styleCode of Object.keys(styleCodes)) {
                        styles[styleCode] = {
                            open: `\x1B[${styleCodes[styleCode][0]}m`,
                            close: `\x1B[${styleCodes[styleCode][1]}m`,
                        };
                    }
                    
                    module.exports = styles;
                    

                    其实用起来很简单。

                    const styles = require("/path/to/styles.js");
                    
                    // Let's say we've got an error:
                    const errorOpen = styles.bold.open + styles.bgRed.open + styles.fgWhite.open;
                    const errorClose = styles.reset.close; // Close everything
                    console.log(errorOpen, "ERROR", errorClose, ": Missing semicolon at line 9.");
                    

                    【讨论】:

                      【解决方案27】:

                      2017:

                      简单的方法,给消息添加时间颜色,你不需要改变你的代码,使用保持你的console.log('msg')或者console.err('error')

                      var clc = require("cli-color");
                      var mapping = {
                        log: clc.blue,
                        warn: clc.yellow,
                        error: clc.red
                      };
                      
                      ["log", "warn", "error"].forEach(function(method) {
                        var oldMethod = console[method].bind(console);
                        console[method] = function() {
                          oldMethod.apply(
                            console,
                            [mapping[method](new Date().toISOString())]
                            .concat(arguments)
                          );
                        };
                      });
                      

                      【讨论】:

                        【解决方案28】:

                        如果您使用的是 Windows CMD,请转到终端属性/颜色(CMD 左上角),然后重新定义攻击性颜色的 RGB 值。就我而言,我相信它是从左边数第五个颜色方块,我将其更改为 (222,222,222)。当前选择的单选按钮是否显示屏幕文本或屏幕背景并不重要,因为您只需重新定义该特定的“系统”颜色。更改颜色后,请不要忘记在单击“确定”之前选择背景或文本的首选颜色。

                        更改后,来自 Node(在我的情况下为 Ember)的所有这些微红色消息都清晰可见。

                        【讨论】:

                          【解决方案29】:

                          在 ubuntu 中,您可以简单地使用颜色代码:

                          var sys = require('sys');
                          process.stdout.write("x1B[31m" + your_message_in_red + "\x1B[0m\r\n");
                          

                          【讨论】:

                          • 为什么不用require
                          • 那是几年前的事了。这是stdout写入的必要条件,现在可能已经默认导入了。
                          • 啊,好的。我只是好奇,因为它不像 sys 在任何地方被使用。不过,现在实际上没有必要!
                          【解决方案30】:

                          node-colorify

                          提供以彩色打印文本以及进行文本格式化(例如粗体、闪烁等)的功能。

                          【讨论】:

                          • 虽然您提供的链接可能会回答问题。最好将解决方案的基本部分直接放在答案中,以防链接页面将来过期。
                          猜你喜欢
                          • 1970-01-01
                          • 2019-02-06
                          • 1970-01-01
                          • 2011-03-14
                          • 1970-01-01
                          • 1970-01-01
                          • 2016-03-04
                          • 2015-06-16
                          相关资源
                          最近更新 更多