Socket
Socket
Sign inDemoInstall

ansicolor

Package Overview
Dependencies
0
Maintainers
2
Versions
94
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    ansicolor

The final solution to the ANSI color/style management. Works in browsers!


Version published
Weekly downloads
33K
increased by1.81%
Maintainers
2
Install size
28.1 kB
Created
Weekly downloads
 

Readme

Source

ansicolor

Build Status Coverage Status npm devDependencies Status

A quality library for the ANSI color/style management. Small. Clean. No dependencies.

npm install ansicolor

What For

  • String coloring with ANSI escape codes
  • Solves the style hierarchy problem (where 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! It sucks. That is 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

Safe Mode (default)

ansi = require ('ansicolor')
console.log ('foo' + ansi.green (ansi.inverse (ansi.bgBrightCyan ('bar')) + 'baz') + 'qux')
console.log (ansi.underline.bright.green ('foo' + ansi.dim.red.bgBrightCyan ('bar'))) // method chaining

Nice Mode (by request)

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 may alter global objects causing potential hard-to-debug compatibility issues.

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

Supported Styles

'foreground colors'
    .black.red.green.yellow.blue.magenta.cyan.white
'background colors'
    .bgBlack.bgRed.bgGreen.bgYellow.bgBlue.bgMagenta.bgCyan.bgWhite
'bright background colors'
    .bgBrightBlack.bgBrightRed.bgBrightGreen.bgBrightYellow.bgBrightBlue.bgBrightMagenta.bgBrightCyan.bgBrightWhite
'styles'
    .bright.dim.italic.underline.inverse // your platform should support italic

You also can use these method names programmatically:

ansi.names // [ 'black', 'bgBlack', 'bgBrightBlack', 'red', 'bgRed', ...

Removing ANSI Styles From Strings

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

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 parsed = ansi.parse ('foo'.bgBrightRed.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 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: 'red', bright: true },
        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:

ansi.rgb = {

    black:   [0,     0,   0],
    red:     [204,   0,   0],
    green:   [0,   204,   0],
    yellow:  [204, 102,   0],
    blue:    [0,     0, 255],
    magenta: [204,   0, 204],
    cyan:    [0,   153, 255],
    white:   [255, 255, 255]
}

ansi.rgbBright = {

    black:   [0,     0,   0],
    red:     [255,  51,   0],
    green:   [51,  204,  51],
    yellow:  [255, 153,  51],
    blue:    [26,  140, 255],
    magenta: [255,   0, 255],
    cyan:    [0,   204, 255],
    white:   [255, 255, 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 string = 'foo' + ('bar'.red.underline.bright.inverse + 'baz').bgGreen
const parsed = ansi.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!

See Also

Keywords

FAQs

Last updated on 19 Jul 2017

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc