1.1.3 • Published 3 years ago

@silva97/ansi v1.1.3

Weekly downloads
4
License
MIT
Repository
github
Last release
3 years ago

npm package Travis CI

@silva97/ansi

This package implements a tag function to parse template strings and add ANSI escape sequences to use colors and text styles on terminal. (read about template strings)

// Example
const { ansi } = require('@silva97/ansi');

console.log(ansi`%{f.green}Hello %{f.red;bold;under}World!`);

Output:
terminal-output

Installation

npm install @silva97/ansi
# Or using yarn:
yarn add @silva97/ansi

ansi tags

The ansi tags follows the format %{...}, it's similar to notation ${...} of template strings to expands the content of an expression on the string. But ansi tags is used to output ANSI escapes.

The color name is specified using the format mode.color. Example f.blue will be set the foreground color to blue.

ModeANSI codeDescription
f3Foreground color
F9Light foreground color
b4Background color

ColorANSI code
black0
red1
green2
yellow3
blue4
violet5
purple5
cyan6
white7

You can also specify styles to text. Example: %{bold;strike}Hello!.

StyleANSI codeDescription
normal0Resets to normal style
bold1Bold text
italic3Italic text
under4underline text
blink5Blinks the text
invert7Inverts background and foreground colors
strike9strike text

Warning: Some styles, like blink and strike, will not work on all terminals. (i.e. VS code integrated terminal)

Note: You can also specify the style numbers instead of the names. Example: %{31;1} will be translated to \x1b[31;1m (same as %{f.red;bold}).

It's yet template strings!

Using ansi tag function you can yet use ${} expressions inside yours strings. Example:

const { ansi } = require('@silva97/ansi');

const name = 'Luiz Felipe';

console.log(ansi`Your name is %{f.green;bold}${name}%{normal}!`);

You can easy disable colors!

You can simple disable the colors of the output if you set ansi.enabled to false. For example:

const { ansi } = require('@silva97/ansi');

ansi.enabled = false;
const name = 'Luiz Felipe';

console.log(ansi`Your name is %{f.green;bold}${name}%{normal}!`);
// Output: "Your name is Luiz Felipe!"

It's will print the text without colors.

Purify text from ANSI escapes

If you previous has been escaped an text, but need the raw text back. You just need to use the purify() function and it will remove all ANSI escapes from the text.

const { ansi, purify } = require('@silva97/ansi');

const name = 'Luiz Felipe';
const welcome = ansi`Your name is %{f.green;bold}${name}%{normal}!`;

console.log(welcome);         // Colored text
console.log(purify(welcome)); // Normal text