Giter Club home page Giter Club logo

chalk's Introduction



Chalk


Terminal string styling done right

Coverage Status npm dependents Downloads





Highlights

Install

npm install chalk

IMPORTANT: Chalk 5 is ESM. If you want to use Chalk with TypeScript or a build tool, you will probably want to use Chalk 4 for now. Read more.

Usage

import chalk from 'chalk';

console.log(chalk.blue('Hello world!'));

Chalk comes with an easy to use composable API where you just chain and nest the styles you want.

import chalk from 'chalk';

const log = console.log;

// Combine styled and normal strings
log(chalk.blue('Hello') + ' World' + chalk.red('!'));

// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold('Hello world!'));

// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));

// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));

// Nest styles of the same type even (color, underline, background)
log(chalk.green(
	'I am a green line ' +
	chalk.blue.underline.bold('with a blue substring') +
	' that becomes green again!'
));

// ES2015 template literal
log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);

// Use RGB colors in terminal emulators that support it.
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
log(chalk.hex('#DEADED').bold('Bold gray!'));

Easily define your own themes:

import chalk from 'chalk';

const error = chalk.bold.red;
const warning = chalk.hex('#FFA500'); // Orange color

console.log(error('Error!'));
console.log(warning('Warning!'));

Take advantage of console.log string substitution:

import chalk from 'chalk';

const name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
//=> 'Hello Sindre'

API

chalk.<style>[.<style>...](string, [string...])

Example: chalk.red.bold.underline('Hello', 'world');

Chain styles and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that chalk.red.yellow.green is equivalent to chalk.green.

Multiple arguments will be separated by space.

chalk.level

Specifies the level of color support.

Color support is automatically detected, but you can override it by setting the level property. You should however only do this in your own code as it applies globally to all Chalk consumers.

If you need to change this in a reusable module, create a new instance:

import {Chalk} from 'chalk';

const customChalk = new Chalk({level: 0});
Level Description
0 All colors disabled
1 Basic color support (16 colors)
2 256 color support
3 Truecolor support (16 million colors)

supportsColor

Detect whether the terminal supports color. Used internally and handled for you, but exposed for convenience.

Can be overridden by the user with the flags --color and --no-color. For situations where using --color is not possible, use the environment variable FORCE_COLOR=1 (level 1), FORCE_COLOR=2 (level 2), or FORCE_COLOR=3 (level 3) to forcefully enable color, or FORCE_COLOR=0 to forcefully disable. The use of FORCE_COLOR overrides all other color support checks.

Explicit 256/Truecolor mode can be enabled using the --color=256 and --color=16m flags, respectively.

chalkStderr and supportsColorStderr

chalkStderr contains a separate instance configured with color support detected for stderr stream instead of stdout. Override rules from supportsColor apply to this too. supportsColorStderr is exposed for convenience.

modifierNames, foregroundColorNames, backgroundColorNames, and colorNames

All supported style strings are exposed as an array of strings for convenience. colorNames is the combination of foregroundColorNames and backgroundColorNames.

This can be useful if you wrap Chalk and need to validate input:

import {modifierNames, foregroundColorNames} from 'chalk';

console.log(modifierNames.includes('bold'));
//=> true

console.log(foregroundColorNames.includes('pink'));
//=> false

Styles

Modifiers

  • reset - Reset the current style.
  • bold - Make the text bold.
  • dim - Make the text have lower opacity.
  • italic - Make the text italic. (Not widely supported)
  • underline - Put a horizontal line below the text. (Not widely supported)
  • overline - Put a horizontal line above the text. (Not widely supported)
  • inverse- Invert background and foreground colors.
  • hidden - Print the text but make it invisible.
  • strikethrough - Puts a horizontal line through the center of the text. (Not widely supported)
  • visible- Print the text only when Chalk has a color level above zero. Can be useful for things that are purely cosmetic.

Colors

  • black
  • red
  • green
  • yellow
  • blue
  • magenta
  • cyan
  • white
  • blackBright (alias: gray, grey)
  • redBright
  • greenBright
  • yellowBright
  • blueBright
  • magentaBright
  • cyanBright
  • whiteBright

Background colors

  • bgBlack
  • bgRed
  • bgGreen
  • bgYellow
  • bgBlue
  • bgMagenta
  • bgCyan
  • bgWhite
  • bgBlackBright (alias: bgGray, bgGrey)
  • bgRedBright
  • bgGreenBright
  • bgYellowBright
  • bgBlueBright
  • bgMagentaBright
  • bgCyanBright
  • bgWhiteBright

256 and Truecolor color support

Chalk supports 256 colors and Truecolor (16 million colors) on supported terminal apps.

Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying {level: n} as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red).

Examples:

  • chalk.hex('#DEADED').underline('Hello, world!')
  • chalk.rgb(15, 100, 204).inverse('Hello!')

Background versions of these models are prefixed with bg and the first level of the module capitalized (e.g. hex for foreground colors and bgHex for background colors).

  • chalk.bgHex('#DEADED').underline('Hello, world!')
  • chalk.bgRgb(15, 100, 204).inverse('Hello!')

The following color models can be used:

  • rgb - Example: chalk.rgb(255, 136, 0).bold('Orange!')
  • hex - Example: chalk.hex('#FF8800').bold('Orange!')
  • ansi256 - Example: chalk.bgAnsi256(194)('Honeydew, more or less')

Browser support

Since Chrome 69, ANSI escape codes are natively supported in the developer console.

Windows

If you're on Windows, do yourself a favor and use Windows Terminal instead of cmd.exe.

Origin story

colors.js used to be the most popular string styling module, but it has serious deficiencies like extending String.prototype which causes all kinds of problems and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative.

Related

Maintainers

chalk's People

Contributors

aslilac avatar bokub avatar calebboyd avatar farnabaz avatar hyperupcall avatar kevva avatar ksxgithub avatar lightnerdev avatar litomore avatar lukeapage avatar m4ttsch avatar marado avatar marionebl avatar martinheidegger avatar mischah avatar nazrhyn avatar noamokman avatar paulmelnikow avatar pedrottimark avatar popey456963 avatar qix- avatar richienb avatar saadq avatar seanmonstar avatar simenb avatar sindresorhus avatar stevemao avatar stroncium avatar thefourtheye avatar toonijn 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  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

chalk's Issues

Possible error created in linux

We are seeing this happen in chalk:

node_modules/gulp-ruby-sass/node_modules/chalk/node_modules/escape-string-regexp/index.js:4
throw new TypeError('Expected a string');
    ^

This was not previously happening. Appears to be related to the changes made 3 days ago. I cannot reproduce this in OSX

The command we're running is gulp sass, which apparently depends on chalk.

Use `bold` by default on Windows

On Windows the blue color by default is pretty unreadable. Even though this isn't really something we should care about as it's a system issue, I'm tired of being trolled about it on various repos.

Normal and bold (bold is really just bright) state:
screen shot 2014-07-13 at 22 58 47

All the colors are pretty dim by default:

screen shot 2014-07-13 at 22 59 04

Thoughts?

// @jbnicolai @jonschlinkert

I also wonder if this could/should be fixed in libuv. ?

0.5.0

  • Draft changelog
  • Add benchmark #21
  • Manually compatibility check popular dependents
  • Release
  • Tweet/G+ about release
  • Have some gummibears

Does not work when piped into bunyan

Colors are stripped when piped into bunyan. Colors still works though. It should still maintain its color through bunyan.

var colors   = require('colors')
var chalk    = require('chalk')

console.log(chalk.blue('test'))
console.log('test'.blue)

.format support

It would be nice to have format as part of the API

console.log(chalk.underline.red.format("Detected %s Error(s)", errors.length));

8-bit/24-bit color support

\e[38;2;{R};{G};{B}m is allegedly the ISO-8613-3 standard for 24-bit colors. Would love to have some real color in the terminal. 256-color mode is more complicated, but also would be good to have support for.

Wikipedia is surprisingly helpful on these ANSI color codes.

0.5.1

I suggest we release version 0.5.1, which will incorporate the bugfix merged in #33

chalk.reset doesn't work?

Hi, I tried to use chalk.reset() to reset my formatted string, but somehow the color is still applied and doesn't get removed.
Is this intended?

multiple chalk functions share the same _styles array

I'd been doing this with chalk 0.4:

var COLORS = {
  INFO: chalk.bold.green,
  WARN: chalk.bold.yellow,
  ERROR: chalk.bold.bgRed,
  // etc
}

Upgrading to 0.5, I find that all of the functions I've stored are all set to apply the styles of the last on in the object.

`reset` order inconsistency

This outputs in yellow:

console.log(chalk.yellow.reset('unicorn'));

This without a style:

console.log(chalk.reset.yellow('unicorn'));

Our docs say the styles aren't order dependent, but with reset they clearly are.

@jbnicolai thoughts on how this should be handled?

Access specific style types

I want to provide an API that would allow users to pick a color they want text in and use that color with this library to colorize. For example, here is a crude way:

var color = 'blue' // string comes from library user
var str = 'hello!' // computed string
var style = chalk.styles[color]
console.log(style.open + str + style.close)

What would be awesome is if there was a way to tell if style was a color and not something like dim (since I just want them to change the colors). Perhaps chalk.colorStyles[color]? Bonus points if I could take the same string ("blue") and get the blue background style. Currently I would have to do: chalk.styles['bg' + color[0].toUppperCase() + color.substr(1)]

Having less dependencies

When i was importing chalk into a module of mine to add colors I was suprised it added 9 modules to my dependency tree.

This seems quite expensive for a simple feature.

To work around this I created a "fork" ( https://github.com/Raynos/term-color#motivation ) with less features.

I'm not sure if chalk is interested in having less dependencies. This would allow me to deprecate my fork but might go against what chalk is as it means removing features.

256 color support?

I made a drop-in replacement for chalk that has 256 color support and a few other things.
https://github.com/ccheever/chalk256

Are you interested in adding any of that to chalk? I can create a pull request, but would have to do a bunch of work to make the code match your style, etc., so wanted to ask before putting in the time.

Chalk has-color issue with bower installation

One of my own builds just failed based on a missing dependency inside chalk. I don't believe this is a problem with my configuration, but I'm wondering if someone else has seen this issue before and if this is with chalk, has-color, or truly my code. Sample failing build:

https://travis-ci.org/jprystowsky/example-hyper-angular-project/builds/22654213

The failure would seem to come from this line: https://github.com/sindresorhus/chalk/blob/master/index.js#L4

It's confusing, though, because the package.json seems to reference has-color.

Coloring stdout and stderr in node

I guess this in not chalk fault, but I'm still puzzled.

I would like stderr in red fo a clear differentiation. However :

var chalk = require('chalk');

console.log('msg on stdout');         <-- black
console.error('msg on stderr');       <-- black

console.log(chalk.styles.blue.open);  <-- I expect to set stdout to blue (for test)

console.log('msg on stdout');         <-- blue
console.error('msg on stderr');       <-- blue, why ?

console.error(chalk.styles.red.open);  <-- I expect to set stderr to red

console.log('msg on stdout');         <-- red, why ?
console.error('msg on stderr');       <-- red

node.js console documentation explicitely states that log goes to stdout and error to stderr. So how comes colors are set for both outputs ?

Add support for TrueColors (24bit RGB)

Colors in terminal

It's a common confusion about terminal colors... Actually we have this:

  • plain ascii
  • ansi escape codes (16 color codes with bold/italic and background)
  • 256 color palette (216 colors+16gray + ansi) (colors are 24bit)
  • 24bit true color (888 colors (aka 16 milion))
    printf "\x1b[${bg};2;${red};${green};${blue}m\n"

The 256 color palete is configured at start, and it's a 666 cube of
colors, each of them defined as a 24bit (888 rgb) color.

This means that current support can only display 256 different colors
in the terminal, while truecolor means that you can display 16 milion
different colors at the same time.

Truecolor escape codes doesnt uses a color palete. It just specifies the
color itself.

Here's a test case:

printf "\x1b[38;2;255;100;0mTRUECOLOR\x1b[0m\n"

Keep in mind that it is possible to use both ';' and ':' as parameters delimiter.

According to Wikipedia[1], this is only supported by xterm and konsole.

[1] https://en.wikipedia.org/wiki/ANSI_color

Here are terminals discussions:

Now supporting truecolor

But there are bunch of libvte-based terminals for GTK2 so they are listed in the another section.

Parsing ANSI color sequences, but approximating them to 256 palette

Note about colour differences: a) RGB axes are not orthogonal, so you cannot use sqrt(R^2+G^2+B^2) formula, b) for colour differences there is more correct (but much more complex) CIEDE2000 formula (which may easily blow up performance if used blindly) [2].

[2] neovim/neovim#793 (comment)

NOT supporting truecolor

Terminal multiplexers

[3] Currently you can use tmux_escape option as a workaround if you want true color in shell run under tmux. No true color in tmux statusline though.

Here are another console programs discussions:

Supporting True Color:

Not supporting True Color:

Whether this is a bug!

In master, it works well. But in child_process, it work fail.

I use forever-monitor to start child process.

`enabled` is global state

Using chalk from a library I know I always want colours enabled as it is explicitly requested to begin with. But doing require('chalk').enabled = true would be bad pratice as this enforce the setting globally and possibly interfere with other libraries using chalk and depending on the auto-detection.

It would be useful to be able to set this option in some isolated way.

FWIW, I usually do it like this

  1. less typing
  2. stands out more visually
  3. I'm usually not worrying about conflicts with jQuery in Node.js
var $ = require('chalk');

// style a string
console.log(  $.blue('Hello world!')  );

// combine styled and normal strings
console.log(  $.blue('Hello'), 'World' + $.red('!')  );

// compose multiple styles using the chainable API
console.log(  $.blue.bgRed.bold('Hello world!')  );

// pass in multiple arguments
console.log(  $.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz')  );

// nest styles
console.log(  $.red('Hello', $.underline.bgBlue('world') + '!')  );

// nest styles of the same type even (color, underline, background)
console.log(  $.green('I am a green line ' + $.blue('with a blue substring') + ' that becomes green again!')  );

supportsColor

chalk.supportsColor is on false whereas package supports-color installed in global and run from command line says true.

Ubuntu 14.10 default gnome terminal & guake.

Maximum call stack size exceeded using yeoman remote

I'm trying to fetch the latest files from the wordpress repo using a yeoman generator, the function looks something like this:

WpGenerator.prototype.getWordpress = function getWordpress() {
    var done = this.async();

    this.log.writeln('Getting WordPress v' + this.wpVersion);

    this.remote('wordpress', 'wordpress', this.wpVersion, function (err, remote) {
        if (err) {
            done(err);
        }
        remote.directory('.', '.');
        done();
    });
};

However half way through the copy process I get this error:

c:\Users\Jahvi\AppData\Roaming\npm\node_modules\yo\node_modules\chalk\chalk.js:30
var obj = defineProps(function self(str) {
RangeError: Maximum call stack size exceeded

I guess there's some sort of recursion going on that's hitting the max call stack size since there are so many files to copy? Not sure if it's an error with yeoman.

Improve performance

I don't have specific other than that I was upgrading my server's trycatch version and it was very slow. Over a couple hours, I tracked the issue down to trycatch's coloring and then to the chalk module itself.

Removing just the line that adds coloring took my 3k unit tests from 30s down to 10s. The colors module doesn't have this problem. Not sure what the difference is. Looked through the source, but it looked like every time a color is accessed you're doing a dynamic getter?

chalk sets background to black instead of previous color (Windows)

I don't know if there's a solution to that, but:

  • Change the default background color of the console on Windows to anything but black
  • Use chalk to change the background color of any string

...and every text after that has a black background instead of the custom default color - but only the text.

Can this be fixed? I know that npm has the same problem though.

Yellow and Magenta do not display in powershell

I'm not sure what should be done about this, if anything.

Yellow isn't too much of a problem since it displays as white but magenta actually displays as the same colour as the powershell background which isn't exactly ideal.

The two options, as far as I can see, are:

  1. leave it up to developers to use what is supported
    • In this case I think a notice about platform compatibility should be added to the readme
  2. Use the 'intense' versions of these colours (they work)
    • Possibility of only using if on windows (although that will make chalk messy which is something I think you are very keen to avoid)
    • changes '\x1b[35m' to '\x1b[95m'

In addition to those colours italic, underline, inverse and strikethrough do not work on windows so I think something in the readme should note that.

Support multiline strings

It would be nice if chalk support strings with multiple lines (\n).

Meanwhile the workaround would something like:

function formatMessage( str ) {
    return String( str ).split( "\n" ).map(function( s ) {
        return chalk.magenta( s );
    }).join( "\n" );
}

It would be better to only use chalk.magenta( str ); and get all the color on all the string lines

Browser Support

Does Chalk run in a browser? If not are there plans to get it running in a browser with something like Browserify?

.hasColor(string)?

i wanna check if a string has a custom color, if not, add some other color.

Work with falsy values Like 0.

I Expected chalk.yellow(0); to output a yellow "0", which wasn't the case. Now I have to do something like chalk.yellow(number.toString());. It would be neat if this was handled in a smarter way.

1.0.0

We should get out an 1.0.0 soon.

Some tasks that needs to be done before hand (please fill in if I left out something):

  • #36
  • #31 no idea what's going on there but I suspect it has nothing to do with us and more to do with npm
  • Readme improvements. Better description. The text feels a bit crude. And anything else that could make Chalk easier to get started with and use.
  • #46
  • Anything feature wise we're missing?
  • chalk/supports-color#13
  • Changelog
  • Some manual testing with popular consumers like Bower, Gulp.

// @jbnicolai

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.