Coder Social home page Coder Social logo

doowb / ansi-colors Goto Github PK

View Code? Open in Web Editor NEW
430.0 6.0 30.0 128 KB

Easily add ANSI colors to your text and symbols in the terminal. ansi-colors is the official ansi styling library for gulp. Used by hundreds of projects, including enquirer, vscode, codeql, azure data studio, aws-cdk, redwoodjs, leaflet, mocha, and many others.

License: MIT License

JavaScript 88.10% TypeScript 11.90%
node nodejs colors ansi-colors ansi red blue green cyan yellow

ansi-colors's Introduction

ansi-colors Donate NPM version NPM monthly downloads NPM total downloads Linux Build Status

Easily add ANSI colors to your text and symbols in the terminal. A faster drop-in replacement for chalk, kleur and turbocolor (without the dependencies and rendering bugs).

Please consider following this project's author, Brian Woodward, and consider starring the project to show your ❤️ and support.

Install

Install with npm:

$ npm install --save ansi-colors

image

Why use this?

ansi-colors is the fastest Node.js library for terminal styling. A more performant drop-in replacement for chalk, with no dependencies.

Usage

const c = require('ansi-colors');

console.log(c.red('This is a red string!'));
console.log(c.green('This is a red string!'));
console.log(c.cyan('This is a cyan string!'));
console.log(c.yellow('This is a yellow string!'));

image

Chained colors

console.log(c.bold.red('this is a bold red message'));
console.log(c.bold.yellow.italic('this is a bold yellow italicized message'));
console.log(c.green.bold.underline('this is a bold green underlined message'));

image

Nested colors

console.log(c.yellow(`foo ${c.red.bold('red')} bar ${c.cyan('cyan')} baz`));

image

Nested styling bug

ansi-colors does not have the nested styling bug found in colorette, chalk, and kleur.

const { bold, red } = require('ansi-styles');
console.log(bold(`foo ${red.dim('bar')} baz`));

const colorette = require('colorette');
console.log(colorette.bold(`foo ${colorette.red(colorette.dim('bar'))} baz`));

const kleur = require('kleur');
console.log(kleur.bold(`foo ${kleur.red.dim('bar')} baz`));

const chalk = require('chalk');
console.log(chalk.bold(`foo ${chalk.red.dim('bar')} baz`));

Results in the following

(sans icons and labels)

image

Toggle color support

Easily enable/disable colors.

const c = require('ansi-colors');

// disable colors manually
c.enabled = false;

// or use a library to automatically detect support
c.enabled = require('color-support').hasBasic;

console.log(c.red('I will only be colored red if the terminal supports colors'));

Strip ANSI codes

Use the .unstyle method to strip ANSI codes from a string.

console.log(c.unstyle(c.blue.bold('foo bar baz')));
//=> 'foo bar baz'

Available styles

Note that bright and bright-background colors are not always supported.

Colors Background Colors Bright Colors Bright Background Colors
black bgBlack blackBright bgBlackBright
red bgRed redBright bgRedBright
green bgGreen greenBright bgGreenBright
yellow bgYellow yellowBright bgYellowBright
blue bgBlue blueBright bgBlueBright
magenta bgMagenta magentaBright bgMagentaBright
cyan bgCyan cyanBright bgCyanBright
white bgWhite whiteBright bgWhiteBright
gray
grey

(gray is the U.S. spelling, grey is more commonly used in the Canada and U.K.)

Style modifiers

  • dim

  • bold

  • hidden

  • italic

  • underline

  • inverse

  • strikethrough

  • reset

Aliases

Create custom aliases for styles.

const colors = require('ansi-colors');

colors.alias('primary', colors.yellow);
colors.alias('secondary', colors.bold);

console.log(colors.primary.secondary('Foo'));

Themes

A theme is an object of custom aliases.

const colors = require('ansi-colors');

colors.theme({
  danger: colors.red,
  dark: colors.dim.gray,
  disabled: colors.gray,
  em: colors.italic,
  heading: colors.bold.underline,
  info: colors.cyan,
  muted: colors.dim,
  primary: colors.blue,
  strong: colors.bold,
  success: colors.green,
  underline: colors.underline,
  warning: colors.yellow
});

// Now, we can use our custom styles alongside the built-in styles!
console.log(colors.danger.strong.em('Error!'));
console.log(colors.warning('Heads up!'));
console.log(colors.info('Did you know...'));
console.log(colors.success.bold('It worked!'));

Performance

Libraries tested

  • ansi-colors v3.0.4
  • chalk v2.4.1

Mac

MacBook Pro, Intel Core i7, 2.3 GHz, 16 GB.

Load time

Time it takes to load the first time require() is called:

  • ansi-colors - 1.915ms
  • chalk - 12.437ms

Benchmarks

# All Colors
  ansi-colors x 173,851 ops/sec ±0.42% (91 runs sampled)
  chalk x 9,944 ops/sec ±2.53% (81 runs sampled)))

# Chained colors
  ansi-colors x 20,791 ops/sec ±0.60% (88 runs sampled)
  chalk x 2,111 ops/sec ±2.34% (83 runs sampled)

# Nested colors
  ansi-colors x 59,304 ops/sec ±0.98% (92 runs sampled)
  chalk x 4,590 ops/sec ±2.08% (82 runs sampled)

Windows

Windows 10, Intel Core i7-7700k CPU @ 4.2 GHz, 32 GB

Load time

Time it takes to load the first time require() is called:

  • ansi-colors - 1.494ms
  • chalk - 11.523ms

Benchmarks

# All Colors
  ansi-colors x 193,088 ops/sec ±0.51% (95 runs sampled))
  chalk x 9,612 ops/sec ±3.31% (77 runs sampled)))

# Chained colors
  ansi-colors x 26,093 ops/sec ±1.13% (94 runs sampled)
  chalk x 2,267 ops/sec ±2.88% (80 runs sampled))

# Nested colors
  ansi-colors x 67,747 ops/sec ±0.49% (93 runs sampled)
  chalk x 4,446 ops/sec ±3.01% (82 runs sampled))

About

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Running Tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

$ npm install && npm test
Building docs

(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)

To generate the readme, run the following command:

$ npm install -g verbose/verb#dev verb-generate-readme && verb

Related projects

You might also be interested in these projects:

Contributors

Commits Contributor
48 jonschlinkert
42 doowb
6 lukeed
2 Silic0nS0ldier
1 dwieeb
1 jorgebucaran
1 madhavarshney
1 chapterjason

Author

Brian Woodward

License

Copyright © 2019, Brian Woodward. Released under the MIT License.


This file was generated by verb-generate-readme, v0.8.0, on July 01, 2019.

ansi-colors's People

Contributors

alan-agius4 avatar bitjson avatar dominykas avatar doowb avatar imhoffd avatar jonschlinkert avatar jorgebucaran avatar lukeed avatar madhavarshney avatar mindplay-dk avatar silic0ns0ldier avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ansi-colors's Issues

Does not support `keyword`

When I switched from chalk to ansi-colors, I couldn't use ansi.keyword('hotpink') like I was using in chalk.

Not a big deal (a little sad as I liked hotpink, but red is fine), but I would suggest removing the 'drop-in' qualifier, either removing it completely or replacing it with something like 'simpler'. Maybe removing the bullet-point in the readme.

That or adding .keyword support. Cheers!

metadata suggestions

Add something like the following to the repository description: ansi-colors is the official ansi styling library for gulp, and is used by hundreds of other projects, including mocha and enquirer.

Failed to minify

Trying to build a react proeject that uses this module and ran into the following issue

`Creating an optimized production build...
Failed to compile.

Failed to minify the code from this file:

    ./node_modules/ansi-colors/index.js:3 

`

No longer works in browser with Webpack 5

Webpack 5 no longer provides polyfills for NodeJS packages. In my case I get Uncaught ReferenceError: process is not defined from this line. I.e., it's process.platform that fails.

I'm running an app built with Create React App, which is why I think the previous line referencing process.env seems to work.

Document Windows support

Hi,
Could you add a sentence in the README explaining if this library works with Windows (or other platforms that do not support ANSI escape codes)? After a quick code overview, it seems that it does not perform any detection logic and just uses the ANSI codes. Does it work with Windows?

enabled is const and cannot be assigned.

Try to disable color mode in my Typescript code.
import * as colors from "ansi-colors"; colors.enabled = false;
It pops up this error
[ts] Cannot assign to 'enabled' because it is a constant or a read-only property.

Nested Colors example does not work

Both locally and online with RunKit, this example does not work:

var c = require("ansi-colors")
c.yellow('foo', c.red.bold('red'), 'bar', c.cyan('cyan'), 'baz')

It only produces foo in yellow.

What were the breaking changes, if any, in v4?

There is no CHANGELOG/HISTORY file, and the releases have no information. A major semver version change implies there were breaking changes. Could you please let us know what those were? Thank you

screenshot

Creating a screenshot for the readme.

image

Fallback color when a given color (e.g. "bright" variants) are not available

If I chain colors like so:

colors.green.greenBright

will it fall-back to "green" if "greenBright" isn't available?

I wanted to test this myself, but wasn't sure how to force-disable "brights" in my terminal.

If this isn't possible it would be a nice feature to consider. I'm wary of using the brights when setting colors on a project that's going to be used by others, because I don't know what will happen if it's not available.

Thanks for maintaining this great package!

TypeScript Typings

This is just a 'nice-to-have' request, since DefinitelyTyped has already got this covered.
Having it directly in the library would eliminate the need for a triple slash directive and another dependency for people using TypeScript. (similar argument for people using Flow I guess).

Render bug in bound methods

The following example has an unexpected render bug.

const { red } = require("ansi-colors")

const boundRedBold = red.bold

console.log(
  red.blue.bold("Blue Bold"),
  boundRedBold("Red Bold") 
)

screen shot 2018-08-23 at 11 29 27

It seems boundRedBold's internal stack should not be jumbled up as a result of calling red.blue.bold().

usage section doesn't really explain how to use

what is the type of this colors object? and all these color functions, how do i use them? would like to know without having to run the code. (sure this info is out there somewhere, but it absolutely belongs in README as well.)

Duplicate packages detected in the ansicolors project on Tag: 4.1.1

Issue: We say a project has duplicated dependencies if any package dependency occurs multiple times in the dependency tree. After analyzing the dependency tree, we have detected duplicate packages in your project.
ansi-colors
object.assign
supports-color
string-width
strip-ansi
ansi-regex

Questions: We are conducting a research study on the duplicated package dependencies in JS projects. We were curious:

  1. Will you remove the duplicates mentioned above? (Yes/No), and why?:
  2. Do you have any additional comments? (If so, please write it down):

For any publication or research report based on this study, we will share all responses from developers in an anonymous way. Both your projects and personal information will be kept confidential.

Rationale: When a JS application depends on too many packages or on multiple versions of the same package, its attack surface can grow dramatically; hackers can get a higher chance of successfully exploiting the vulnerabilities inside those packages (or versions), and escalating the potential damage. The unnecessary and duplicated dependencies can also make JS projects bloat and lead to extra memory/computation overhead. Therefore, JS application developers are recommended to remove unused and duplicated packages from their projects, in order to eliminate the security risks unnecessarily incurred by those dependencies.

Steps to reproduce:

  • Execute the “npm ls --all” command to print the dependency tree of the project containing all the libraries and their corresponding versions
  • Check if any library exists more than once in the tree

Suggested Solution: Execute the “npm dedupe” command to reduce the number of duplicate packages, or to manually modify package.json files

Resource:
https://docs.npmjs.com/cli/v7/commands/npm-dedupe

Update benchmark results in the readme

We just released Chalk 3 with some large performance improvements. This is what I'm seeing with Chalk 3 and Node.js 12:

~/Downloads/ansi-colors/bench master*
❯ node index

# All Colors
  ansi-colors x 150,257 ops/sec ±0.95% (90 runs sampled)
  chalk x 490,982 ops/sec ±0.48% (94 runs sampled)

# Chained colors
  ansi-colors x 20,122 ops/sec ±0.55% (92 runs sampled)
  chalk x 412,857 ops/sec ±1.12% (92 runs sampled)

# Nested colors
  ansi-colors x 52,308 ops/sec ±0.49% (91 runs sampled)
  chalk x 93,588 ops/sec ±0.26% (92 runs sampled)

Would be great if you could re-run the benchmark on your machine and update the readme.

escape colors on stdout

when I test a cli app and use node.js child_process module to spawn a command and assert against the stdout out, chalk correctly escapes the colors, ansi-colors doesn't.

In other words this library is not suitable for testing CLI packages, libraries. Please check how chalk handles it.

Minor edit needed

Usage

const c = require('ansi-colors');

console.log(c.red('This is a red string!')); 
console.log(c.green('This is a **red** string!'));   <==== should read "green" string
console.log(c.cyan('This is a cyan string!'));
console.log(c.yellow('This is a yellow string!'));

Color sequences incorrectly terminate in Chrome

After some initial testing, I picked ansi-colors from the wealth of color-packages, as it appeared to be the only package that would load and work in the browser.

But it looks like I've run into a problem - take this simple example:

import colors from "ansi-colors";

console.log(`this is ${colors.bgRed.white("white")}\nthis is ${colors.bgGreen.white("green")}\nall good?`);

When run in a terminal, as expected:

image

However, when run in the Chrome or Edge DevTools console:

image

Also, when running in Firefox, it doesn't correctly detect color support:

image

It happens with just background and no text color too:

console.log(`this is ${colors.bgRed("white")}\nthis is ${colors.bgGreen("green")}\nall good?`);

However, it only happens with background colors and not with text colors - so this:

console.log(`this is ${colors.red("red")}\nthis is ${colors.green("green")}\nall good?`);

Looks fine in Chrome:

image

Here's a running example.

It could be a bug in Chrome and Edge, I suppose?

Is browser support officially supported by the library?

I mean, the README doesn't say it is, and the only reason I assumed it did, was because I noticed there's a ansi-colors-es6 fork with the description "Easily add ANSI colors to your node terminal or browser console". (and yes, this fork has the same problem.)

Bug when nesting colors causing styles to not be applied

I got into a situation where I need to nest color styles and didn't get the result I was expecting. I wasn't sure how to fix it, so I'm just creating a bug ticket. You can reproduce it running the code below here.

const c = require("ansi-colors")
console.log(c.red(`R${c.green(`G${c.blue("B")}G`)}R`))

Thanks.

open to a PR using proxy?

The changes would use latest es features, so it would definitely be a major bump.

The advantage of using proxy is that - the way I'm implementing it - methods will only be created when or if they are called the first time.

In benchmarks, it's screaming fast both on initial load:

ansi-colors: 0.798ms
chalk: 11.025ms
clorox: 1.031ms

and when the methods are called subsequently:

# All Colors
  ansi-colors x 31,995 ops/sec ±1.23% (89 runs sampled)
  chalk x 9,510 ops/sec ±1.93% (82 runs sampled)
  clorox x 1,447 ops/sec ±2.35% (78 runs sampled)

# Stacked colors
  ansi-colors x 10,066 ops/sec ±0.81% (89 runs sampled)
  chalk x 1,910 ops/sec ±1.69% (81 runs sampled)
  clorox x 579 ops/sec ±2.02% (66 runs sampled)

# Nested colors
  ansi-colors x 14,256 ops/sec ±0.49% (94 runs sampled)
  chalk x 4,259 ops/sec ±2.00% (83 runs sampled)
  clorox x 677 ops/sec ±2.17% (76 runs sampled)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.