Giter Club home page Giter Club logo

cli-color's Introduction

Build status Tests coverage npm version

cli-color

Yet another colors and formatting for the console solution

Colors, formatting and other goodies for the console. This package won't mess with built-ins and provides neat way to predefine formatting patterns, see below.

Installation

$ npm install cli-color

Usage

Usage:

var clc = require("cli-color");

Output colored text:

console.log(clc.red("Text in red"));

Styles can be mixed:

console.log(clc.red.bgWhite.underline("Underlined red text on white background."));

Styled text can be mixed with unstyled:

console.log(clc.red("red") + " plain " + clc.blue("blue"));

Styled text can be nested:

console.log(clc.red("red " + clc.blue("blue") + " red"));

Best way is to predefine needed stylings and then use it:

var error = clc.red.bold;
var warn = clc.yellow;
var notice = clc.blue;

console.log(error("Error!"));
console.log(warn("Warning"));
console.log(notice("Notice"));

Note: No colors or styles are output when NO_COLOR env var is set

Supported are all ANSI colors and styles:

Styles

Styles will display correctly if font used in your console supports them.

  • bold
  • italic
  • underline
  • blink
  • inverse
  • strike

Colors

ForegroundBackground
blackbgBlack
redbgRed
greenbgGreen
yellowbgYellow
bluebgBlue
magentabgMagenta
cyanbgCyan
whitebgWhite
Bright variants
ForegroundBackground
blackBrightbgBlackBright
redBrightbgRedBright
greenBrightbgGreenBright
yellowBrightbgYellowBright
blueBrightbgBlueBright
magentaBrightbgMagentaBright
cyanBrightbgCyanBright
whiteBrightbgWhiteBright
xTerm colors (256 colors table)

Not supported on Windows and some terminals. However if used in not supported environment, the closest color from basic (16 colors) palette is chosen.

Usage:

var msg = clc.xterm(202).bgXterm(236);
console.log(msg("Orange text on dark gray background"));

Color table:

Screenshot 2022-07-04 at 12 28 18

Reset

Terminal can be cleared with clc.reset

process.stdout.write(clc.reset);

Erase

clc.erase.screen

Entire screen

process.stdout.write(clc.erase.screen);
clc.erase.screenLeft

Left portion of a screen

process.stdout.write(clc.erase.screenLeft);
clc.erase.screenRight

Right portion of a screen

process.stdout.write(clc.erase.screenRight);
clc.erase.line

Current line

process.stdout.write(clc.erase.line);
clc.erase.lineRight

Right portion of current line

process.stdout.write(clc.erase.lineRight);
clc.erase.lineLeft

Left portion of current line

process.stdout.write(clc.erase.lineLeft);

Move around functions

clc.move(x, y)

Move cursor x columns and y rows away. Values can be positive or negative, e.g.:

process.stdout.write(clc.move(-2, -2)); // Move cursors two columns and two rows back
clc.move.to(x, y)

Absolute move. Sets cursor position at x column and y row

process.stdout.write(clc.move.to(0, 0)); // Move cursor to first row and first column in terminal window
clc.move.up(n)

Move cursor up n rows

process.stdout.write(clc.move.up(2));
clc.move.down(n)

Move cursor down n rows

process.stdout.write(clc.move.down(2));
clc.move.right(n)

Move cursor right n columns

process.stdout.write(clc.move.right(2));
clc.move.left(n)

Move cursor left n columns

process.stdout.write(clc.move.left(2));
clc.move.lines(n)

Move cursor n lines forward if n is positive, otherwise n lines backward, and place it at line beginning

process.stdout.write(clc.move.lines(2));
clc.move.top

Move cursor to top of a screen

process.stdout.write(clc.move.top);
clc.move.bottom

Move cursor to bottom of a screen

process.stdout.write(clc.move.bottom);
clc.move.lineBegin

Move cursor to begin of a line

process.stdout.write(clc.move.lineBegin);
clc.move.lineEnd

Move cursor to end of a line

process.stdout.write(clc.move.lineEnd);

Terminal characteristics

clc.windowSize.width

Returns terminal width

clc.windowSize.height

Returns terminal height

Additional functionalities

clc.slice(str[, begin[, end]])

Slice provided string with preservation of eventual ANSI formatting

var clc = require("cli-color");

var str = clc.bold("foo") + "bar" + clc.red("elo");
var sliced = clc.slice(str, 1, 7); // Same as: clc.bold('oo') + 'bar' + clc.red('e')

clc.strip(formatedText)

Strips ANSI formatted string to plain text

var ansiStrip = require("cli-color/strip");

var plain = ansiStrip(formatted);

clc.getStrippedLength(str)

Get actual length of ANSI-formatted string

var clc = require("cli-color");

var str = clc.bold("foo") + "bar" + clc.red("elo");
clc.getStrippedLength(str); // 9

clc.art(text, styleConf)

Create a text-graphical art. Within styleConf, string replacements needs to be defined, which are then used to convert text to styled graphical text.

var text = ".........\n" + ". Hello .\n" + ".........\n";
var style = { ".": clc.yellowBright("X") };

process.stdout.write(clc.art(text, style));

clc.columns(data[, options])

Outputs aligned table of columns.

data is expected to be an array (or other iterable structure) of rows, where each row is also an array (or other iterable structure) of content to display.

Supported options:

  • sep: Custom colums separator (defaults to |)
  • columns: Per column customizations, as e.g. [{ align: 'right' }, null, { align: 'left' }]:
    • align: Possible options: 'left', 'right (efaults to 'left')
var clc = require("cli-color");

process.stdout.write(
  clc.columns([
    [clc.bold("First Name"), clc.bold("Last Name"), clc.bold("Age")],
    ["John", "Doe", 34],
    ["Martha", "Smith", 20],
    ["Jan", "Kowalski", 30]
  ])
);

/* Outputs:

First Name | Last Name | Age
John       | Doe       | 34
Martha     | Smith     | 20
Jan        | Kowalski  | 30
*/
throbber(write, interval[, format])

Writes throbber string to write function at given interval. Optionally throbber output can be formatted with given format function

var setupThrobber = require("cli-color/throbber");

var throbber = setupThrobber(function (str) { process.stdout.write(str); }, 200);

throbber.start();

// at any time you can stop/start throbber
throbber.stop();

Tests

$ npm test

Security contact information

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.

Contributors

  • @rentalhost (David Rodrigues)
    • Help with support for nested styles. Introduction of clc.art module, and significant improvements to tests coverage
  • @StreetStrider
    • Implementation of sophistcated clc.slice functionality, and introduction of clc.getStrippedLength utility

Get professional support for cli-color with a Tidelift subscription
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.

cli-color's People

Contributors

callumlocke avatar danbell avatar jcabot21 avatar medikoo avatar ralphtheninja avatar stevenmhunt avatar streetstrider avatar vesln 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

cli-color's Issues

Mixed Styles results in Unresolved function or method

If styles are mixed like in this example
console.log(clc.red.bgWhite("Red text on white background."));
I am seeing a minor warning
Unresolved function or method bgWhite()

This happens in a Typescript Project.

node: 21.7.1
cli-color: 2.0.4
@types/cli-color: 2.0.6

trim function flaw

Good day!
It seemes that additional trim function does not handles fine xterm-sequences:

clc = require('cli-color');
trim = require('cli-color/lib/trim');
A = clc.red('AAA');
> '\u001b[31mAAA\u001b[39m'
trim(A)
> 'AAA'
B = clc.xterm(218)('BBB');
> '\u001b[38;5;218mBBB\u001b[39m'
trim(B)
> '\u001b[38;5;218mBBB'

Maybe trim regexp is not enough powerful for this.
BTW, thanks for that lib, it's really easy-to-use and awesome!

Split into few packages

  • cli-color should be purely about style and color
  • cli-utils (or similar) should be about any small operations as erase and move, for meta retireval, any ansi processing like slice, strip, getStrippedLength
  • cli-art (or similar) to create text graphical art
  • cli-table (or similar) to output table

On the way throbber probably should be dropped, at least current form doesn't reflect good design, and there's way more powerful progress handling provided by cli-progress-footer

trim (chop) styled string to width

Hello.
Sometimes I need to trim to certain width string which have been already styled and contains control sequences. If use naive string.slice it very probably will break the styling. Is it possible to solve this issue under the cli-color's roof, so I could be able to:

var slice = require('cli-color/slice')
styled = slice(styled, 0, 80) // ← works like String.prototype.slice, but respects styling

?

It will be the feature I would use. Sometimes to workaround this I need to implement some lispy-constructors which save styles and still allows to chop/slice (something like this):

var s = [ 'long', [ clc.red, 'string' ], 'long' ]
slice_then_style(s)

Using cli-color as in a module

Here is a very simple example:

File node_functions.js:

var clc = require('/usr/lib/node_modules/cli-color');

module.exports = {
  pass: function () {
    console.log(clc.bgGreen.white.bold("PASS"))
  },
  fail: function () {
    console.log(clc.bgRed.white.bold("FAIL"))
  }
};

File test.js:

var tools = require('node_functions.js');
console.log(tools.fail());

The expected result would be simply the word FAIL in bold white over red backgroud.

However the result is:

conferences ssh 2015-06-29 14-07-38

I have no idea where the "undefined" comes from.

Running [email protected] with node v0.10.39

Problem testing the "throbber"

When I run npm test it works with 99.65% of tests, but throbber.js fails.

throbber.js
Error: spawn UNKNOWN
    at exports._errnoException (util.js:746:11)
    at ChildProcess.spawn (child_process.js:1155:11)
    at exports.spawn (child_process.js:988:9)
    at module.exports. (D:\projects\cli-color\test\throbber.js:10:11)
    at D:\projects\cli-color\node_modules\tad\lib\run.js:71:7
    at Object.Reduce.processCb (D:\projects\cli-color\node_modules\tad\node_modules\deferred\ext\array\reduce.js:101:18)
    at Object.Reduce [as continue] (D:\projects\cli-color\node_modules\tad\node_modules\deferred\ext\array\reduce.js:67:18)
    at Object.Reduce.init (D:\projects\cli-color\node_modules\tad\node_modules\deferred\ext\array\reduce.js:59:16)
    at Object.Reduce (D:\projects\cli-color\node_modules\tad\node_modules\deferred\ext\array\reduce.js:39:14)
    at Array.module.exports (D:\projects\cli-color\node_modules\tad\node_modules\deferred\ext\array\reduce.js:143:9)
    at run (D:\projects\cli-color\node_modules\tad\lib\run.js:39:18)
    at D:\projects\cli-color\node_modules\tad\lib\run.js:106:7

    at process._tickCallback (node.js:355:11)16:06:50.558  -  throbber.js: Formatted
Error: spawn UNKNOWN
    at exports._errnoException (util.js:746:11)
    at ChildProcess.spawn (child_process.js:1155:11)
    at exports.spawn (child_process.js:988:9)
    at module.exports.Formatted (D:\projects\cli-color\test\throbber.js:27:11)
    at D:\projects\cli-color\node_modules\tad\lib\run.js:71:7
    at Object.Reduce.processCb (D:\projects\cli-color\node_modules\tad\node_modules\deferred\ext\array\reduce.js:101:18)
    at Object.Reduce [as continue] (D:\projects\cli-color\node_modules\tad\node_modules\deferred\ext\array\reduce.js:67:18)
    at Object.Reduce.init (D:\projects\cli-color\node_modules\tad\node_modules\deferred\ext\array\reduce.js:59:16)
    at Object.Reduce (D:\projects\cli-color\node_modules\tad\node_modules\deferred\ext\array\reduce.js:39:14)
    at Array.module.exports (D:\projects\cli-color\node_modules\tad\node_modules\deferred\ext\array\reduce.js:143:9)
    at run (D:\projects\cli-color\node_modules\tad\lib\run.js:39:18)
    at D:\projects\cli-color\node_modules\tad\lib\run.js:106:7

    at process._tickCallback (node.js:355:11)

I'm running on Windows 8.1.

├── [email protected]
├─┬ [email protected]
│ ├── [email protected]
│ └── [email protected]
├─┬ [email protected]
│ ├─┬ [email protected]
│ │ ├─┬ [email protected]
│ │ │ └── [email protected]
│ │ └── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ └── [email protected]
├─┬ [email protected]
│ ├── [email protected]
│ ├─┬ [email protected]
│ │ └── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├─┬ [email protected]
│ │ └─┬ [email protected]
│ │   ├── [email protected]
│ │   └── [email protected]
│ ├── [email protected]
│ ├─┬ [email protected]
│ │ ├── [email protected]
│ │ └── [email protected]
│ ├── [email protected]
│ └─┬ [email protected]
│   └── [email protected]
├─┬ [email protected]
│ └── [email protected]
├─┬ [email protected]
│ ├── [email protected]
│ ├─┬ [email protected]
│ │ └── [email protected]
│ ├── [email protected]
│ ├─┬ [email protected]
│ │ └─┬ [email protected]
│ │   ├── [email protected]
│ │   └── [email protected]
│ ├── [email protected]
│ ├─┬ [email protected]
│ │ └── [email protected]
│ └── [email protected]
└─┬ [email protected]
  └── [email protected]

"not a function" error when binding

I tried to create a function that returns a function which will log things in color:

const logRed = createLogger(clc.red);
function createLogger(colorizeFn) {
	return function() {
		var args = getArgs(arguments);
		args[0] = colorizeFn(args[0].toString());
		console.log.apply(console.log, args);
	}
}
logRed("sometimes this doesnt work...");

Seemingly randomly, it thinks "colorizeFn" is not a function. What is going on here?

nested brightness shouldn't be preserved

adding the last two line to your sample code basic.js

console.log('Styled text can be nested:');
console.log(clc.red('red ' + clc.blue('blue') + ' red'));
console.log(clc.red('red ' + clc.blueBright('blue') + ' red bright')+clc.yellow(' bright?'));
console.log(clc.redBright('red ') + ' bright?');

In the third line, the "red bright" piece of string appear red bright, but it shouldn't.. IMHO
the yellow one appear just yellow, as it should be.

Also the last default part of last line appear not bright, as it should be.

Seems that brihtness isn't cleared in close sequence when nested.

I'm using (and I have to use) the standard windows cmd

image

es5-ext, cli-color related error

Good day. I have strange error which can only be reproduced in special environment. I've tried to determine the problem myself, but I do not know cli-color and es5-ext packages well enough.

Here's the problem: My project uses console-ultimate package of my own, depends on cli-color (depends on es5-ext). Everything works fine. But when I start project in forever I have constraint error:

RangeError: Count must be >= 0
    at String.module.exports (/home/<project>/opt/<project>/node_modules/console-ultimate/node_modules/cli-color/node_modules/es5-ext/string/#/repeat/shim.js:11:23)
    at Function.module.exports.defineProperties.reset (/home/<project>/opt/<project>/node_modules/console-ultimate/node_modules/cli-color/index.js:109:17)
    at Object.<anonymous> (/home/<project>/opt/<project>/node_modules/console-ultimate/src/console/clear.js:5:30)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/<project>/opt/<project>/node_modules/console-ultimate/src/Console.js:18:10)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
error: Forever detected script exited with code: 8

console-ultimate extensively uses cli-color, but the only feature fails is .clear, I workaround it by removing var reset = require('cli-color').reset in .clear.

This issue reproduces on remote machines with Ubuntu and Centos.

Do you have any ideas why this code fails? Maybe there's conflict in prototypes?

Opt-in String.prototype extension

It would be cool to have to ways of requiring it:

require('cli-color').apply()

and

require('cli-color')

The first one would extend String.prototype and expose the same methods:

'test'.red.bgWhite.underline

semver versioning dependency breaks on es5-ext 0.10.52

Throws the following exception when a newer version of es5-ext is installed

internal/modules/cjs/loader.js:583
    throw err;
    ^

Error: Cannot find module 'es5-ext/object/assign'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
    at Function.Module._load (internal/modules/cjs/loader.js:507:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (/home/me/some-project/backend/node_modules/d/index.js:5:23)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (/home/me/some-project/backend/node_modules/cli-color/index.js:3:9)

I was able to get it working with...

// package.json
"resolutions": {
  "cli-color/**/es5-ext": "0.10.51"
}

Feature suggestion - environment variable to disable functionality

I know it sounds strange to have the feature essentially be "disable all the functionality provided by your module" - but would be a nice capability to have since most apps using it wouldn't provide that function themselves.

Reason is to be able to easily turn off all the highlighting/color codes/etc. for batch execution (log files/etc) generated by code using cli-color, since right now, it makes for an ugly log file.

I don't know the best way to do this, I initially tried just setting TERM=dumb since that has historically worked nicely with ncurses/etc. Maybe that would be a workable approach here - can you check for TERM=dumb explicitly, and if so, blank out much of the functions of the module so that it would be suitable for output in a plain text log file?

Include .trim() in cli-color directly.

Currently we need require the cli-color/trim to support trim. And it is a little redundant, for me. Why I'll require a feature (trim) inside a major feature (cli-color)? It's like I need to include cli-color/width to get the console width, because cli-color is focused in color.

Currently:

var cli = require("cli-color"),
    trim = require("cli-color/trim");

console.log(trim(cli.blue("hello")));

Suggestion:

var cli = require("cli-color");

console.log(cli.trim(cli.blue("hello")));

Version:

  • 0.4.x Implements this feature;
  • 1.0.x Remove support to cli-color/trim way;

xterm-colors are not unique

there are duplicate colors inside xterm-colors.

[ "000000", "0000ff", "00ff00", "00ffff", "808080", "ff0000", "ff00ff", "ffff00", "ffffff" ]

this is in general not a big deal, unlike you do encoding and decoding with this array, which is exactly what i do (for very unknown reasons) .

https://github.com/andreas83/colorcoder/

Reset

Hi,

console.log(clc.bgBright.bgBlack.red(req.method + " " + req.url + ": notFound()") );

doesn't reset its background. Subsequent console.log() calls also have the bgBright.bgBlack background.

My current work-around: append \033[0m to the end of the console.log() call.

Allow "color inside color".

Example:

cli.whiteBright("Hello " + cli.blackBright("World") + "!");

Turns to:

<whiteBright>Hello </whiteBright><blackBright>World</blackBright><whiteBright>!</whiteBright>

Currently it turns to:

<whiteBright>Hello </whiteBright><blackBright>World</blackBright><white>!</white>

image

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.