• Stars
    star
    653
  • Rank 68,968 (Top 2 %)
  • Language
    JavaScript
  • License
    ISC License
  • Created over 13 years ago
  • Updated over 2 years ago

Reviews

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

Repository Details

Colors and formatting for the console

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.

More Repositories

1

memoizee

Complete memoize/cache solution for JavaScript
JavaScript
1,681
star
2

modules-webmake

Bundle CommonJS/Node.js modules for web browser
JavaScript
409
star
3

deferred

Modular and fast Promises implementation for JavaScript
JavaScript
363
star
4

event-emitter

Environment agnostic event emitter solution for JavaScript
JavaScript
228
star
5

es6-symbol

ECMAScript 6 Symbol polyfill
JavaScript
180
star
6

es5-ext

ECMAScript extensions (with respect to upcoming ECMAScript features)
JavaScript
162
star
7

domjs

DOM template engine for client and server
JavaScript
143
star
8

es6-template-strings

Compile and resolve template strings notation as specified in ES6
JavaScript
78
star
9

es6-map

Map collection as specified in ECMAScript6
JavaScript
73
star
10

next-tick

Environment agnostic nextTick polyfill
JavaScript
72
star
11

es6-set

Set collection as specified in ECMAScript 6
JavaScript
46
star
12

log

Universal logging utility
JavaScript
43
star
13

d

Property descriptor factory
JavaScript
42
star
14

type

Runtime validation and processing of JavaScript types
JavaScript
35
star
15

es6-weak-map

WeakMap collection as specified in ECMAScript6
JavaScript
29
star
16

dbjs

In-Memory Database Engine for JavaScript
JavaScript
28
star
17

path2

Modular and extended version of Node's path package
JavaScript
25
star
18

duration

Time duration utilities for JavaScript
JavaScript
24
star
19

find-requires

Find all require() calls. Fast and solid implementation backed with direct scanner and esprima ast parser
JavaScript
24
star
20

serverless-plugin-vpc-eni-cleanup

Cleanup of VPC network interfaces on stage removal
JavaScript
20
star
21

fs2

Complement to Node.js fs package
JavaScript
19
star
22

controller-router

Environment agnostic URL router
JavaScript
19
star
23

es6-iterator

Iterator abstraction as specified in ECMAScript6
JavaScript
18
star
24

npm-cross-link

npm packages cross linker (automate 'npm link' installs)
JavaScript
17
star
25

serverless-plugin-dynamodb-autoscaling

Auto configure autoscaling for preconfigured Dynamodb tables within Serverless project
JavaScript
16
star
26

lru-queue

Size limited queue based on LRU algorithm
JavaScript
15
star
27

serverless-plugin-reducer

Serverless plugin: Reduce Node.js lambda package so it contains only lambda dependencies
JavaScript
14
star
28

date-from-timezone

Construct dates with timezone context
JavaScript
14
star
29

tad

JavaScript test suite
JavaScript
13
star
30

esniff

Low footprint JavaScript source code parser
JavaScript
12
star
31

bespoke-notes

Display slide notes in Bespoke.js presentations
JavaScript
11
star
32

plain-promise

Plain (educational) promise implementation
JavaScript
10
star
33

time-uuid

Universally unique identifier based on current time in short not standard UUID format
JavaScript
10
star
34

node-ext

Node.js extensions
JavaScript
9
star
35

asynchronous-javascript-interfaces

Asynchronous JavaScript Interfaces (march 2014 presentation)
HTML
9
star
36

observable-array

Configure observable arrays
JavaScript
8
star
37

ag-sorted

Sort 'ag' output by filename
JavaScript
8
star
38

bespoke-sync

Cross-client synchronization for Bespoke.js presentations
JavaScript
8
star
39

bespoke-substeps

Substeps for Bespoke.js presentations
JavaScript
7
star
40

cjs-vs-amd-benchmark

Compare load time of CommonJS and AMD style modules
JavaScript
7
star
41

github-news-reader

Reader for GitHub private News Feed
JavaScript
7
star
42

soundcloud-playlist-manager

Playlist Manager for SoundCloud (prototype)
JavaScript
7
star
43

irc-notifier

IRC email notifications (keywords/phrases mentions)
JavaScript
7
star
44

fb-calendar-puzzle

Facebook interview question
JavaScript
7
star
45

punycode2

Modular version of punycode package
JavaScript
6
star
46

observable-value

Atomic observable value interface
JavaScript
6
star
47

site-tree

A View engine
JavaScript
6
star
48

git-list-updated

Resolve list of updated (and existing) files in given repository branch
JavaScript
6
star
49

log-node

Node.js log generator for "log" engine
JavaScript
6
star
50

child-process-ext

Node.js child_process extensions
JavaScript
6
star
51

github-release-from-cc-changelog

Create/Update Github release notes from a changelog
JavaScript
5
star
52

ncjsm

CJS (Node.js) style modules resolver
JavaScript
5
star
53

bespoke-history

URL (window.history based) router for Bespoke presentation engine
JavaScript
5
star
54

i18n2

Custom gettext solution
JavaScript
5
star
55

observable-set

Configure observable set collections
JavaScript
5
star
56

webmake-coffee

Develop CoffeeScript applications with Webmake
JavaScript
5
star
57

xlint

Powerful CLI for any lint (JSLint/JSHint +) solution
JavaScript
5
star
58

serverless-plugin-transpiler

Serverless plugin: Transpile lambda files during packaging step
JavaScript
4
star
59

2-thenable

Convert object to thenable
JavaScript
4
star
60

es3-ext

ECMAScript 3 extensions (with respect to ECMAScript 5 standard)
JavaScript
4
star
61

movejs

Rename/Move CJS module(s) and update all affected requires
JavaScript
4
star
62

browserstack-tape-runner

Run tests configured with tape in browsers with BrowserStack
JavaScript
4
star
63

observable-map

Configure observable map collections
JavaScript
4
star
64

el-screen

Window configurations manager for Emacs
Emacs Lisp
4
star
65

es-async

ES2017 async functions compiler
JavaScript
4
star
66

sprintf-kit

printf parser and basic formatter
JavaScript
4
star
67

microtime-x

Microseconds time for JavaScript (cross-environment)
JavaScript
3
star
68

exec-batch

Batch execution of shell commands
JavaScript
3
star
69

event-source

EventSource polyfill as clean NPM module
JavaScript
3
star
70

timers-ext

Timers extensions
JavaScript
3
star
71

split-utf8-file

Splits utf8 encoded file into smaller files of fixed size
JavaScript
3
star
72

kind-of-javascript

"Kind Of JavaScript" WarsawJS presentation
HTML
3
star
73

webmake-yaml

Require YAML files with Webmake
JavaScript
3
star
74

dbjs-ext

Extension types for DBJS engine
JavaScript
3
star
75

csslint-next

Customized version of CSSLint
JavaScript
3
star
76

querystring2

Modular and env agnostic version of Node's querystring
JavaScript
3
star
77

cli-progress-footer

Dynamic progress footer bar for any CLI application
JavaScript
3
star
78

clock

Indicate and co-ordinate JavaScript time events
JavaScript
3
star
79

essentials

Essential initialization for every JavaScript process
JavaScript
2
star
80

html-template-to-dom

Resolve HTML string with ES6 template style inserts into DOM
JavaScript
2
star
81

engine-sniff

Engine detection utilities
JavaScript
2
star
82

aws-step-functions-inspector

Dumps all events of specified state machine instance in human readable format
JavaScript
2
star
83

data-fragment

Engine agnostic live data fragments synchronisation
JavaScript
2
star
84

dom-ext

DOM extensions
JavaScript
2
star
85

github-actions-workflows

Reusable GitHub Actions Workflows
JavaScript
2
star
86

meetjs.pl

Meetjs.pl Website
JavaScript
2
star
87

log-aws-lambda

log4 log writer for AWS Lambda environment
JavaScript
2
star
88

process-utils

Utilities for Node.js process handling
JavaScript
2
star
89

stream-promise

Promise that's a also a Node.js Stream
JavaScript
2
star
90

prettier-elastic-vars-v1.0

Prettier with alternative formatting for var, let & const declarations
JavaScript
2
star
91

set-collection

Set collection type for JavaScript
JavaScript
2
star
92

xlint-sublime

XLint build system for Sublime Text2
Python
2
star
93

git-branch-deploy

Setup repository branch for deployment
JavaScript
2
star
94

html-site-tree

Configure views with HTML for SiteTree engine
JavaScript
2
star
95

aws-lambda-handler

Essential AWS Lambda handler setup
JavaScript
2
star
96

html-dom-event-ext

Extensions and utilities related to HTML DOM Events interfaces
JavaScript
1
star
97

google-group-reader

Reader for any Google Group
JavaScript
1
star
98

test-serverless

Each project in different git branch
JavaScript
1
star
99

eslint-config-medikoo-es3

Opinionated ESLint configuration for ES3+ projects
JavaScript
1
star
100

css-aid

Light, standards focused CSS preprocessor
JavaScript
1
star