首页 文章

如何更改node.js的控制台字体颜色?

提问于
浏览
329

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

28 回答

  • 9

    在ubuntu中,您只需使用颜色代码:

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

    在Node.js中有一些用于更改控制台字体颜色的模块,最受欢迎的是:

    chalk用法:

    npm安装粉笔

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

    colors用法:

    npm安装颜色

    var colors = require('colors/safe'); // does not alter string prototype
    console.log(colors.red('This String Will Display RED'));
    

    有几种颜色可供选择,以及文本格式如 Bold 和Italic .

    很多人都注意到他们在 Colors 改变了 String prototype ,如果你更喜欢单独使用你的原型,你会想要使用cli-colorchalk

    cli-color用法:

    npm安装cli-color

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

    cli-colorchalk都需要更多的输入,但是你会得到类似的结果(到颜色)而不添加String原型 . 两者都支持很好的颜色范围,格式(粗体/斜体等)并且有 unit tests .

    随便挑选 .

  • 0

    这是Windows 10的一种方法(可能是7),它改变了cmd,npm终端本身的颜色方案(主题),而不仅仅是特定应用程序的控制台输出 .

    我找到了工作的Windows插件 - Color Tool,它可能是在Windows下开发的 . 有关说明,请访问link .

    我将colortool目录添加到系统环境路径变量中,现在每当我启动终端(NodeJs命令提示符,cmd)时它都可用 .

  • 5
    var to_rgb = function (_text, _r, _g, _b) {
        return "\x1b[38;2;" + _r + ";" + _g + ";" + _b + "m" + _text + "\x1b[0m";
    };
    

    此代码有助于设置前景色:\ x1b [38; 2; R; G; Bm

    这可能无法在某处工作

  • 13

    今天有两种方法可以查看更改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 .

    Default colors as used by manakin:

    enter image description here

  • 1

    如果你想直接改变颜色而不用模块试试

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

    首先'\ x1b [36m'将颜色更改为“36”然后再返回到终端颜色“0” .

    Here's a list of ANSI color codes

  • 18

    我重载了控制台方法 .

    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");
    

    输出是 .
    enter image description here

  • 4

    node-colorify

    提供以彩色打印文本的功能,也可以进行粗体,闪烁等文本格式化 .

  • 7

    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

  • 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 重置终端颜色,使其在此之后不再继续为所选颜色 .

    Colors reference

    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 是一个转义序列,将被终端拦截并指示它切换为红色 . 实际上, \x1bnon-printable control character escape 的代码 . 仅处理颜色和样式的转义序列也称为 ANSI escape code 并且是标准化的,因此它们(应该)可以在任何平台上工作 .

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

  • -1

    对于colors的流行替代方案,它不会弄乱String对象的内置方法,我建议检查cli-color .

    包括颜色和可链接样式,如粗体,斜体和下划线 .

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

  • 6
    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);
    
  • 1

    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 ")
    
  • 3

    你也可以使用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.]]`);
    
  • 1

    2017年:

    简单的方法,在消息中添加时间colord,您不需要更改代码,使用keep your 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)
        );
      };
    });
    

    enter image description here

  • 10

    Color codes are as mentioned

    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"
    

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

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

    颜色和效果的顺序似乎并不那么重要,但始终要记住在最后重置颜色和效果 .

  • 576

    我不希望任何依赖这个,只有这些在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

  • 0

    遇到这个问题,想在stdout上使用一些颜色,没有任何依赖 . 这里结合了其他一些很好的答案 .

    这就是我所拥有的 . (需要节点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

  • 1

    这是可用操作(重置,反向,...)的控制台中可用颜色(背景,前景)的列表 .

    const colors = {
     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" //القرمزي
     },
     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(colors.bg.Blue, colors.fg.White , "I am white message with blue background", colors.Reset) ; 
     //don't forget "colors.Reset" to stop this color and return back to the default color
    

    你也可以安装:

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

    IT将为您提供更接近客户端控制台的输出:

    enter image description here

  • 68

    我创建了自己的模块,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"))
    
  • 3

    我真的很喜欢@Daniel的答案,但是console.log 函数与常规console.log的工作方式不同 . 我做了一些更改,现在新函数的所有参数都将传递给console.log(以及颜色代码) .

    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",
    };
    
    const enableColorLogging = function(){
        Object.keys(_colors).forEach(key => {
            console['log' + key] = function(){
                return console.log(_colors[key], ...arguments, _colors.Reset);
            }
        });
    }
    
  • 3

    我为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')}`)
    
  • 235

    为输出着色你可以使用那里的例子:
    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

  • 2

    paint-console

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

    install

    npm install paint-console
    

    usage

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

    demo

  • 24

    没有图书馆没有并发症很简单:

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

    根据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命令提示符 .

    (感谢loganfsmyth在this answer中的repl想法 . )

  • 124

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

    粉笔

    • 高效率

    • 不延长 String.prototype

    • 富有表现力的API

    • 能够嵌套样式

    • 清洁和专注

    • 自动检测颜色支持

    • 积极维护

    • 由5500模块使用

  • -1

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

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

相关问题