• Stars
    star
    119
  • Rank 297,930 (Top 6 %)
  • Language
    JavaScript
  • License
    The Unlicense
  • Created over 8 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A JavaScript ANSI color/style management. ANSI parsing. ANSI to CSS. Small, clean, no dependencies.

ansicolor

Build Status Coverage Status npm dependencies Status

A JavaScript ANSI color/style management. ANSI parsing. ANSI to CSS. Small, clean, no dependencies.

npm install ansicolor

What For

  • String coloring with ANSI escape codes
  • Solves the style hierarchy problem (when other similar tools fail)
  • Parsing/removing ANSI style data from strings
  • Converting ANSI styles to CSS or a Chrome DevTools-compatible output
  • A middleware for your platform-agnostic logging system

Why Another One?

Other tools lack consistency, failing to solve a simple hierarchy problem:

require ('colors') // a popular color utility

console.log (('foo'.cyan + 'bar').red)

pic

WTF?! The bar word above should be rendered in red, but it's not! That sucks. It's because ANSI codes are linear, not hierarchical (as with XML/HTML). A special kind of magic is needed to make this work. Ansicolor does that magic for you:

require ('ansicolor').nice // .nice for unsafe String extensions

console.log (('foo'.cyan + 'bar').red)

pic

Nice!

Crash Course

Importing (as methods):

import { green, inverse, bgLightCyan, underline, dim } from 'ansicolor'
const { green, inverse, bgLightCyan, underline, dim } = require ('ansicolor')

Usage:

console.log ('foo' + green (inverse (bgLightCyan ('bar')) + 'baz') + 'qux')
console.log (underline.bright.green ('foo' + dim.red.bgLightCyan ('bar'))) // method chaining

Importing (as object):

import { ansicolor, ParsedSpan } from 'ansicolor' // along with type definitions
import ansicolor from 'ansicolor'

Nice Mode (not recommended)

const ansi = require ('ansicolor').nice

The ('ansicolor').nice export defines styling APIs on the String prototype directly. It uses an ad-hoc DSL (sort of) for infix-style string coloring. The nice is convenient, but not safe, avoid using it in public modules, as it alters global objects, and that might cause potential hard-to-debug compatibility issues.

console.log ('foo'.red.bright + 'bar'.bgYellow.underline.dim)

Supported Styles

'foreground colors'
    .red.green.yellow.blue.magenta.cyan.white.darkGray.black
'light foreground colors'
    .lightRed.lightGreen.lightYellow.lightBlue.lightMagenta.lightCyan.lightGray
'background colors'
    .bgRed.bgGreen.bgYellow.bgBlue.bgMagenta.bgCyan.bgWhite.bgDarkGray.bgBlack
'light background colors'
    .bgLightRed.bgLightGreen.bgLightYellow.bgLightBlue.bgLightMagenta.bgLightCyan.bgLightGray
'styles'
    .bright.dim.italic.underline.inverse // your platform should support italic

You also can obtain all those style names (for reflection purposes):

const { names } = require ('ansicolor')

names // ['red', 'green', ...

Removing ANSI Styles From Strings

const { strip } = require ('ansicolor')

strip ('\u001b[0m\u001b[4m\u001b[42m\u001b[31mfoo\u001b[39m\u001b[49m\u001b[24mfoo\u001b[0m')) // 'foofoo'

Checking If Strings Contain ANSI Codes

const { isEscaped, green } = require ('ansicolor')

isEscaped ('text')         // false
isEscaped (green ('text')) // true

Converting to CSS/HTML

Inspection of ANSI styles in arbitrary strings is essential when implementing platform-agnostic logging โ€” that piece of code is available under command line interface and in a browser as well. Here's an example of how you would parse a colored string into an array-like structure. That structure can be traversed later to build HTML/JSON/XML or any other markup/syntax.

const { parse } = require ('ansicolor')

const parsed = parse ('foo'.bgLightRed.bright.italic + 'bar'.red.dim)

The ansi.parse () method will return a pseudo-array of styled spans, you can iterate over it with a for ... of loop and convert it to an array with the spread operator (...). Also, there's the .spans property for obtaining the already-spread array directly:

assert.deepEqual (parsed.spans /* or [...parsed] */,

    [ { css: 'font-weight: bold;font-style: italic;background:rgba(255,51,0,1);',
        italic: true,
        bold: true,
        color: { bright: true },
        bgColor: { name: 'lightRed' },
        text: 'foo' },

      { css: 'color:rgba(204,0,0,0.5);',
        color: { name: 'red', dim: true },
        text: 'bar' } ])

Custom Color Themes

You can change default RGB values (won't work in terminals, affects only the ANSIโ†’CSS transformation part):

const ansi = require ('ansicolor')

ansi.rgb = {

    black:        [0,     0,   0],    
    darkGray:     [100, 100, 100],
    lightGray:    [200, 200, 200],
    white:        [255, 255, 255],

    red:          [204,   0,   0],
    lightRed:     [255,  51,   0],
    
    green:        [0,   204,   0],
    lightGreen:   [51,  204,  51],
    
    yellow:       [204, 102,   0],
    lightYellow:  [255, 153,  51],
    
    blue:         [0,     0, 255],
    lightBlue:    [26,  140, 255],
    
    magenta:      [204,   0, 204],
    lightMagenta: [255,   0, 255],
    
    cyan:         [0,   153, 255],
    lightCyan:    [0,   204, 255],
}

Chrome DevTools Compatibility

Web browsers usually implement their own proprietary CSS-based color formats for console.log and most of them fail to display standard ANSI colors. Ansicolor offers you a helper method to convert ANSI-styled strings to browser-compatible argument lists acceptable by Chrome's console.log:

const { bgGreen, red, parse } = require ('ansicolor')

const string = 'foo' + bgGreen (red.underline.bright.inverse ('bar') + 'baz')
const parsed = parse (string)

console.log (...parsed.asChromeConsoleLogArguments) // prints with colors in Chrome!

Here's what the format looks like:

parsed.asChromeConsoleLogArguments // [ "%cfoo%cbar%cbaz",
                                   //   "",
                                   //   "font-weight: bold;text-decoration: underline;background:rgba(255,51,0,1);color:rgba(0,204,0,1);",
                                   //   "background:rgba(0,204,0,1);"
                                   // ]

Play with this feature online: demo page. Open the DevTools console and type expressions in the input box to see colored console output.

Happy logging!

Projects That Use ansicolor

  • Ololog! โ€” a better console.log for the log-driven debugging junkies
  • CCXT โ€” a cryptocurrency trading API with 130+ exchanges
  • Grafana โ€” beautiful monitoring & metric analytics & dashboards

More Repositories

1

crx-hotreload

Chrome Extension Hot Reloader
JavaScript
851
star
2

stacktracey

Parses call stacks. Reads sources. Clean & filtered output. Sourcemaps. Node & browsers.
JavaScript
218
star
3

ololog

A better console.log for the log-driven debugging junkies
JavaScript
215
star
4

panic-overlay

Displays JS errors in browsers. Shows sources. Use with any framework. ๐Ÿ’ฅโœจ
JavaScript
80
star
5

wyg

A new WYSIWYG editing experience for the modern web
JavaScript
76
star
6

as-table

A simple function that prints objects as ASCII tables. Supports ANSI styling and weird Unicode ๐Ÿ’ฉ emojis โ€“ they won't break the layout.
JavaScript
62
star
7

expression

An interactive paint application driven by cellular automation (WebGL)
JavaScript
37
star
8

get-source

Fetch source-mapped sources. Peek by file, line, column. Node & browsers. Sync & async.
JavaScript
28
star
9

string.ify

A small, simple yet powerful JavaScript object stringifier / pretty-printer
JavaScript
26
star
10

what-code-is-faster

A browser-based tool for speedy and correct JS performance comparisons!
TypeScript
24
star
11

react-gpu

React WebGPU Renderer
TypeScript
24
star
12

life

A nice looking version of Life in WebGL
JavaScript
21
star
13

printable-characters

A little helper for handling strings containing zero width characters, ANSI styling, whitespaces, newlines, ๐Ÿ’ฉ, etc.
JavaScript
19
star
14

pipez

Function sequencing reloaded
JavaScript
14
star
15

gop

ะ“ะžะŸะะ˜ะš.EXE (ะ’ะตะฑ-ะฒะตั€ัะธั)
JavaScript
14
star
16

git-slack-notify

Sends Slack notifications for new commits in Git repositories
JavaScript
13
star
17

mole

Mole Simulator
JavaScript
8
star
18

skychat

An example of WebRTC chat/paint app with distributed message history
HTML
8
star
19

es7-object-polyfill

A polyfill for missing Object.values / Object.entries
JavaScript
7
star
20

string.bullet

ASCII-mode bulleting for the list-style data
JavaScript
5
star
21

turing-2d

A toroidal turing machine (WebGL)
JavaScript
5
star
22

parcel-plugin-svg-react

Import SVG as React components (Parcel plugin)
JavaScript
5
star
23

chai-spies-decorators

Chai Spies + ES7 decorators
JavaScript
4
star
24

slack-js-console

A JavaScript interpreter for Slack channels
JavaScript
4
star
25

meta-fields

Meta-annotations for data structures in JavaScript
JavaScript
2
star
26

gop2

ะ“ะžะŸะะ˜ะš-2.EXE
JavaScript
2
star
27

mutko

The simplest context menu translator for Chrome // WIP
JavaScript
2
star