How to use chalk

Comprehensive chalk code examples:

How to use chalk.Chalk:

5
6
7
8
9
10
11
12
13
14
15
16
//
const prefix = require("loglevel-plugin-prefix");
const chalk = require("chalk");


// type LogLevelColorMapType = {
//   [index: string]: chalk.Chalk
// }


const DEFAULT_LOG_LEVEL = "DEBUG";

How to use chalk.yellowBright:

13
14
15
16
17
18
19
20
21
22
  break;
case 'POST':
  coloredRequest = chalk.greenBright(request);
  break;
case 'PUT':
  coloredRequest = chalk.yellowBright(request);
  break;
case 'PATCH':
  coloredRequest = chalk.magentaBright(request);
  break;

How to use chalk.bgYellowBright:

14
15
16
17
18
19
20
21
22
23
    return parts.join(' ');
  },
  success: chalk.bgGreenBright.black('SUCCESS'),
  err: chalk.bgRedBright.white('ERROR'),
  info: chalk.bgBlueBright.white('INFO'),
  warn: chalk.bgYellowBright.black('WARN'),
};

function fatal(e, code = 1) {
  if (typeof e === 'string') {

How to use chalk.__proto__:

59
60
61
62
63
64
65
66
67
68
69
70
71
// // chalk.__proto__ = function () { };


// // color.prototype.green = function () { };
// // color.prototype.blue = function () { };


// chalk.__proto__.green = function () { console.log('green') }
// chalk.__proto__.blue = function () { console.log('blue') }


// chalk.__proto__.bgRed = function () { console.log('bgRed inside green') }
// // chalk.blue.__proto__.bgRed = function () { console.log('bgRed inside blue') }

How to use chalk.bgMagenta:

8
9
10
11
12
13
14
15
16
17
, cancel: chalk.yellow.bold
, fail: chalk.red
, success: chalk.green.bold
, shutdown: chalk.bgYellow.white
, ready: chalk.bgGreen.white.bold
, recover: chalk.bgMagenta.bold
, rebalance: chalk.bgBlue
, purge: chalk.bgRed.white.bold
, evict: chalk.red.bold
}

How to use chalk.bgCyan:

151
152
153
154
155
156
157
158
159
160

```js
const ansiText = chalk.bgRed('🌈') +
        chalk.bgYellow('🦄') +
        chalk.bgGreen('🐘') +
        chalk.bgCyan('🍄') +
        chalk.bgBlue('🎃') +
        chalk.bgMagenta('🐦') +
        chalk.bgRed('🖤') +
        chalk.bgYellow('😳') +

How to use chalk.rgb:

459
460
461
462
463
464
465
466
467
468
        255,
        255,
        255
      )(moment(Date.now()).format(" dddd, DD MMMM YYYY HH:mm:ss "))}]:`
    ),
    chalk.rgb(255, 38, 0)(...args)
  );
},
warn(...args) {
  console.log(

How to use chalk.bgGreenBright:

11
12
13
14
15
16
17
18
19
20
    if (opts && opts.cwd) {
      parts.push('in', color.path(opts.cwd));
    }
    return parts.join(' ');
  },
  success: chalk.bgGreenBright.black('SUCCESS'),
  err: chalk.bgRedBright.white('ERROR'),
  info: chalk.bgBlueBright.white('INFO'),
  warn: chalk.bgYellowBright.black('WARN'),
};

How to use chalk.italic:

18
19
20
21
22
23
24
25
26
  process.stdout.write(
    '\n\nOpen ' +
      chalk.magenta('http://webpack.github.io/analyse/') +
      ' in your browser and upload the stats.json file!' +
      chalk.blue(
        '\n(Tip: ' + chalk.italic('CMD + double-click') + ' the link!)\n\n',
      ),
  );
}

How to use chalk.styles:

How to use chalk.magentaBright:

61
62
63
64
65
66
67
68
69
70
  const mockRoutes = registerRoutes(app)
  mockRoutesLength = mockRoutes.mockRoutesLength
  mockStartIndex = mockRoutes.mockStartIndex

  console.log(
    chalk.magentaBright(
      `\n > Mock Server hot  success! changed  ${path}`
    )
  )
} catch (error) {

How to use chalk.Instance:

137
138
139
140
141
142
143
144
145
146

### chalk.enabled

Color support is automatically detected, as is the level (see `chalk.level`). However, if you'd like to simply enable/disable Chalk, you can do so via the `.enabled` property. When `chalk.enabled` is `true`, `chalk.level` must *also* be greater than `0` for colored output to be produced.

Chalk is enabled by default unless explicitly disabled via `new chalk.Instance()` or `chalk.level` is `0`.

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

```js

How to use chalk.reset:

21
22
23
24
25
26
27
28
29
30
);
babelOptions.babelrc = false;
const SRC_DIR = 'src';
const JS_FILES_PATTERN = '**/*.js*';
const IGNORE_PATTERN = '**/__tests__/**';
const OK = chalk.reset.inverse.bold.green(' DONE ');

const adjustToTerminalWidth = str => {
  const columns = process.stdout.columns || 80;
  const width = columns - stringLength(OK) + 1;

How to use chalk.bgWhite:

121
122
123
124
125
126
127
128
129
130
    ? chalk.red
    : chalk.yellow;
const progress =
  phase === 'in_progress'
    ? chalk.green.bgGreen(DARK_BLOCK_CHAR.repeat(filledBar)) +
      chalk.bgWhite.white(
        LIGHT_BLOCK_CHAR.repeat(MAX_PROGRESS_BAR_CHAR_WIDTH - filledBar),
      ) +
      chalk.bold(` ${(100 * ratio).toFixed(1)}% `) +
      chalk.dim(`(${transformedFileCount}/${totalFileCount})`)

How to use chalk.bgBlueBright:

13
14
15
16
17
18
19
20
21
22
    }
    return parts.join(' ');
  },
  success: chalk.bgGreenBright.black('SUCCESS'),
  err: chalk.bgRedBright.white('ERROR'),
  info: chalk.bgBlueBright.white('INFO'),
  warn: chalk.bgYellowBright.black('WARN'),
};

function fatal(e, code = 1) {

How to use chalk.bgBlackBright:

16
17
18
19
20
21
22
23
24
25
      ? `${label} ${line}`
      : line.padStart(stripAnsi(label).length)
  }).join('\n')
}

const chalkTag = msg => chalk.bgBlackBright.white.dim(` ${msg} `)

exports.log = (msg = '', tag = null) => {
  tag ? console.log(format(chalkTag(tag), msg)) : console.log(msg)
  _log('log', tag, msg)

How to use chalk.level:

129
130
131
132
133
134
135
136
137
138

```js
const ctx = new chalk.constructor({enabled: false});
```

### chalk.level

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:

How to use chalk.bgRedBright:

12
13
14
15
16
17
18
19
20
      parts.push('in', color.path(opts.cwd));
    }
    return parts.join(' ');
  },
  success: chalk.bgGreenBright.black('SUCCESS'),
  err: chalk.bgRedBright.white('ERROR'),
  info: chalk.bgBlueBright.white('INFO'),
  warn: chalk.bgYellowBright.black('WARN'),
};

How to use chalk.supportsColor:

146
147
148
149
150
151
152
153
154
155
0. All colors disabled
1. Basic color support (16 colors)
2. 256 color support
3. Truecolor support (16 million colors)

### chalk.supportsColor

Detect whether the terminal [supports color](https://github.com/chalk/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, add the environment variable `FORCE_COLOR=1` to forcefully enable color or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.

How to use chalk.bgYellow:

6
7
8
9
10
11
12
13
14
15
, replace: chalk.blue
, execute: chalk.blue.bold
, cancel: chalk.yellow.bold
, fail: chalk.red
, success: chalk.green.bold
, shutdown: chalk.bgYellow.white
, ready: chalk.bgGreen.white.bold
, recover: chalk.bgMagenta.bold
, rebalance: chalk.bgBlue
, purge: chalk.bgRed.white.bold

How to use chalk.bgGreen:

7
8
9
10
11
12
13
14
15
16
, execute: chalk.blue.bold
, cancel: chalk.yellow.bold
, fail: chalk.red
, success: chalk.green.bold
, shutdown: chalk.bgYellow.white
, ready: chalk.bgGreen.white.bold
, recover: chalk.bgMagenta.bold
, rebalance: chalk.bgBlue
, purge: chalk.bgRed.white.bold
, evict: chalk.red.bold

How to use chalk.whiteBright:

29
30
31
32
33
34
35
36
37
38
    )
  )
);

console.log(
  whiteBright(
    `> Total app users: ${totalUsers.toLocaleString()}\n> Total Servers: ${client.guilds.cache.size.toLocaleString()}\n---------------------------------\n` +
      `> Discord Verified: ${
        client.user.verified ? "Yes" : "No"
      }`

How to use chalk.inverse:

6
7
8
9
10
11
12
13
14
    punctuator: chalk.grey,
    keyword:    chalk.cyan,
    number:     chalk.magenta,
    regex:      chalk.magenta,
    comment:    chalk.grey.bold,
    invalid:    chalk.inverse
},

codeFrame: asIs,

How to use chalk.enabled:

117
118
119
120
121
122
123
124
125
126

Chain [styles](#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.enabled

Color support is automatically detected, as is the level (see `chalk.level`). However, if you'd like to simply enable/disable Chalk, you can do so via the `.enabled` property.

Chalk is enabled by default unless expicitly disabled via the constructor or `chalk.level` is `0`.

How to use chalk.bgBlue:

145
146
147
148
149
150
151
152
153
154
155
156
global.DELAY_5m = 300000; // 5 minutes delay


function consoleInfo() {
  // eslint-disable-next-line prefer-rest-params
  const args = [].slice.call(arguments);
  const output = chalk.bgBlue.white(`\n>>>>> \n${args}\n<<<<<\n`);
  console.log(output);
}


/**

How to use chalk.redBright:

14
15
16
17
18
19
20
21
22
23
async function warnMessage(message) {
  return console.log(chalk.bgYellow.black(`[${await getCurrentTime()}] Warning >`) + ' ' + chalk.yellow(message));
}

async function errorMessage(message) {
  return console.log(chalk.bgRedBright.black(`[${await getCurrentTime()}] Error >`) + ' ' + chalk.redBright(message));
}

async function broadcastMessage(message, location) {
  return console.log(chalk.inverse(`[${await getCurrentTime()}] ${location} Broadcast >`) + ' ' + message);

How to use chalk.constructor:

126
127
128
129
130
131
132
133
134
Chalk is enabled by default unless expicitly disabled via the constructor or `chalk.level` is `0`.

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

```js
const ctx = new chalk.constructor({enabled: false});
```

### chalk.level

How to use chalk.white:

46
47
48
49
50
51
52
53
54
55
electronProcess.stdout.on('data', data => {
    if (data == EOL) {
        return;
    }

    process.stdout.write(Chalk.blueBright(`[electron] `) + Chalk.white(data.toString()))
});

electronProcess.stderr.on('data', data => 
    process.stderr.write(Chalk.blueBright(`[electron] `) + Chalk.white(data.toString()))

How to use chalk.keyword:

92
93
94
95
96
97
98
99
100
101

```js
const chalk = require('chalk');

const error = chalk.bold.red;
const warning = chalk.keyword('orange');

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