Как показывать красочные сообщения в консоли в Node.js

Одна из проблем, с которыми вы сталкиваетесь при работе в Node.js, заключается в том, что постоянно регистрируемые сообщения, в основном наиболее важные сообщения теряются в случайном порядке с подробным выводом. Цвета полезны на консоли, чтобы сделать более существенные ошибки или просто привлечь внимание к важным ошибкам и другим предупреждениям.

В этой статье вы узнаете, как легко отображать текст в консоли узла с цветами и стилем, с библиотекой или без нее.

Сделай это легко с библиотекой

Если вы не хотите усложнять себя, то, вероятно, вы хотите быть модульным и использовать стороннюю библиотеку для достижения своей цели. В этом случае, чтобы изменить цвет текста в консоли, мы рекомендуем вам модуль colors.js, доступный в NPM. Этот модуль позволяет вам отображать цвет и стиль в вашей консоли node.js с помощью цепных методов (т.е. "text".bgBlue.white.underline):

Чтобы установить модуль colors.js в свой проект, выполните в командной строке Node.js следующую команду:

npm install colors

Предупреждение: не путайте его с другим пакетом с именем colors.js

Читайте больше информации о библиотека и ее документация в официальном репозитории Github здесь.

Цвет текста

По умолчанию добавьте некоторые свойства (со всеми доступными цветами в качестве имени) в String.prototype что делает настройку цветов в консоли довольно простой:

var colors = require('colors');
console.log("The style of this text will be modified".black);
console.log("The style of this text will be modified".red);
console.log("The style of this text will be modified".green);
console.log("The style of this text will be modified".yellow);
console.log("The style of this text will be modified".blue);
console.log("The style of this text will be modified".magenta);
console.log("The style of this text will be modified".cyan);
console.log("The style of this text will be modified".white);
console.log("The style of this text will be modified".gray);

Тем не менее, если вы боитесь расширения String.prototype Вы можете использовать безопасный режим, используя метод non-prototype:

var colors = require('colors/safe');
console.log(colors.black('The style of this text will be modified'));
console.log(colors.red('The style of this text will be modified'));
console.log(colors.green('The style of this text will be modified'));
console.log(colors.yellow('The style of this text will be modified'));
console.log(colors.blue('The style of this text will be modified'));
console.log(colors.magenta('The style of this text will be modified'));
console.log(colors.cyan('The style of this text will be modified'));
console.log(colors.white('The style of this text will be modified'));
console.log(colors.gray('The style of this text will be modified'));

Выполнение любого из предыдущих фрагментов должно привести к следующему результату в консоли:

Пользовательский цвет текста node.js

Фоновый цвет

Стандартный способ добавить цвет фона для некоторого текста в консоли, добавить некоторые свойства (со всеми доступными цветами и префиксом Б.Г. как имя) в String.prototype что делает настройку цветов в консоли довольно простой:

var colors = require('colors');
console.log('The style of this text will be modified'.bgBlack);
console.log('The style of this text will be modified'.bgRed);
console.log('The style of this text will be modified'.bgGreen);
console.log('The style of this text will be modified'.bgYellow);
console.log('The style of this text will be modified'.bgBlue);
console.log('The style of this text will be modified'.bgMagenta);
console.log('The style of this text will be modified'.bgCyan);
console.log('The style of this text will be modified'.bgWhite);
// Change the text color to black
console.log('The style of this text will be modified'.bgWhite.black);
// or "text".black.bgWhite

Тем не менее, если вы боитесь расширения String.prototype Вы можете использовать безопасный режим, используя метод non-prototype:

var colors = require('colors/safe');
console.log(colors.bgBlack('The style of this text will be modified'));
console.log(colors.bgRed('The style of this text will be modified'));
console.log(colors.bgGreen('The style of this text will be modified'));
console.log(colors.bgGreen('The style of this text will be modified'));
console.log(colors.bgYellow('The style of this text will be modified'));
console.log(colors.bgBlue('The style of this text will be modified'));
console.log(colors.bgMagenta('The style of this text will be modified'));
console.log(colors.bgCyan('The style of this text will be modified'));
console.log(colors.bgWhite('The style of this text will be modified'));
// Change the text color to black
console.log(colors.bgWhite.black('The style of this text will be modified'));
// or colors.black.bgWhite("Text")

Выполнение любого из предыдущих фрагментов должно привести к следующему результату в консоли:

Пользовательский цвет фона node.js

Стили текста

Существует 8 доступных стилей для применения с Colors.js:

var colors = require('colors');
console.log('The style of this text will be modified'.reset);
console.log('The style of this text will be modified'.bold);
console.log('The style of this text will be modified'.dim);
console.log('The style of this text will be modified'.italic);
console.log('The style of this text will be modified'.underline);
console.log('The style of this text will be modified'.inverse);
console.log('The style of this text will be modified'.hidden);
console.log('The style of this text will be modified'.strikethrough);

Тем не менее, если вы боитесь расширения String.prototype Вы можете использовать безопасный режим, используя метод non-prototype:

var colors = require('colors/safe');
console.log(colors.reset('The style of this text will be modified'));
console.log(colors.bold('The style of this text will be modified'));
console.log(colors.dim('The style of this text will be modified'));
console.log(colors.italic('The style of this text will be modified'));
console.log(colors.underline('The style of this text will be modified'));
console.log(colors.inverse('The style of this text will be modified'));
console.log(colors.hidden('The style of this text will be modified'));
console.log(colors.strikethrough('The style of this text will be modified'));

Сделай это без библиотеки

Если вы не хотите зависеть от какого-либо модуля, вы можете реализовать свои собственные методы, основанные на следующей информации.

Цвет текста

Чтобы отобразить текст определенного цвета, вам нужно заключить текст в определенные символы, и он будет интерпретирован консолью.

Чтобы понять, как это работает, проанализируйте следующий пример:

var myText = "Hello World";
var startWrapper = "[31m";
var closeWrapper = "[39m";
// Show some text in the console with red Color
console.log(startWrapper + myText + closeWrapper);

Однако, если вы выполните предыдущий код в консоли, это не сработает! как будет выводить простой текст[31mHello World[39m«в консоли. Так в чем же подвох? console.log, чтобы показать вывод, ожидает простую строку в качестве первого параметра (так же, как в примерах Color.js). Поэтому следующий пример должен работать:

// Show some text in the console with red Color
console.log("[31mHello World[39m");

В следующей таблице указан код для каждого доступного отображаемого цвета:

цвет
Начинается с
Заканчивается на
пример
черный[30m? [39m[30mREPLACE-ЭТО? [39m
красный[31m? [39m[31mREPLACE-ЭТО? [39m
зеленый[32m? [39m[32mREPLACE-ЭТО? [39m
желтый[33м? [39m[33мREPLACE-ЭТО?[39m
синий[34м? [39m[34мREPLACE-ЭТО? [39m
фуксин[35m? [39m[35mREPLACE-ЭТО? [39m
Cyan[36m? [39m[36mREPLACE-ЭТО? [39m
белый[37m? [39m[37mREPLACE-ЭТО?[39m
Серый[90m? [39m[90mREPLACE-ЭТО? [39m

Фоновый цвет

Чтобы отобразить текст с определенным цветом фона, вам нужно заключить текст в определенные символы (даже если они уже используют цвет текста), и он будет интерпретироваться консолью.

Цвет фона работает так же, как цвет текста. Однако вместо использования [3x префикс, он использует [4x,

цвет
Начинается с
Заканчивается на
пример
черный[40m? [49m[40mREPLACE-ЭТО? [49m
красный[41m? [49m[41mREPLACE-ЭТО? [49m
зеленый[42m? [49m[42mREPLACE-ЭТО? [49m
желтый[43m? [49m[43mREPLACE-ЭТО?[49m
синий[44m? [49m[44mREPLACE-ЭТО? [49m
фуксин[45m? [49m[45mREPLACE-ЭТО? [49m
Cyan[46m? [49m[46mREPLACE-ЭТО? [49m
белый[47м? [49m[47мREPLACE-ЭТО?[49m

В следующем примере должен отображаться текст с синим фоном и белым цветом:

console.log("[37m[44mOur Code World Rocks[49m[39m");

Стили текста

Чтобы применить некоторые стили текста к вашему тексту, вам нужно заключить текст в определенные символы (в большинстве случаев, чтобы они работали, они уже должны иметь цвет текста), и он будет интерпретироваться консолью.

цвет
Начинается с
Заканчивается на
пример
Сброс[0м? [0м[0мREPLACE-ЭТО? [0м
смелый[1m? [22m[1mREPLACE-ЭТО? [22m
тусклый[2m? [22m[2mREPLACE-ЭТО? [22m
курсивный[3m? [23m[3mREPLACE-ЭТО?[23м
подчеркивание[4м? [24m[4мREPLACE-ЭТО? [24m
обратный[7м? [27m[7мREPLACE-ЭТО? [27m
скрытый[8м? [28m[8мREPLACE-ЭТО? [28m
просачивание[9m? [29m[9mREPLACE-ЭТО? [29m

В следующем примере должен отображаться красный текст с подчеркиванием:

console.log("[4m[31mSome text[39m[24m");
// Or in other order with the same result
console.log("[31m[4mSome text[24m[39m");

Обратите внимание, что (очевидно) символы должны заканчиваться соответственно тому, как они начали ( или наоборот).

Ссылка на основную публикацию
Adblock
detector