LoginSignup
0
0

More than 3 years have passed since last update.

nodeのコマンドプロントのconsole.logで出力に色を付ける

Posted at

はじめに

Nodeでコマンドプロンプトの出力(console.log)に色をつけたかったので、その方法を投稿します。

検索してもwebブラウザのconsoleに色を付ける方法が多くヒットしたので、私と同じように困っている人の助けになれば…(こんなことで困ってないか:joy:)。

結論

色を付けるnpm がありました!!
chalk

npm i chalk

前提条件

環境

  • node v10.16.3
  • npm 6.9.0

使用例

ざっくりと使用例と出力結果を投稿します。
全ての例を投稿するわけではないので詳しく見たい方はchalkのページで確認してください。

色を変える

色を変えたい文字列を、変えたい色の修飾子で囲う
※変えられる色の種類はchalkのページで確認してください。

index.js

const Chalk = require('chalk')
const log = console.log;

//文字の色変更
log(Chalk.red('Hello') + ' World' + Chalk.red('!'));
log(Chalk.blue('Hello Blue world!'));
log(Chalk.green('Hello Green world!'));
log(Chalk.yellow('Hello Yellow world!'));

出力結果
color.png

背景色を変える

色を変えるのとほぼ変わらない。

index.js

const Chalk = require('chalk')
const log = console.log;

//文字の背景色変更
log(Chalk.bgRed('Hello') + ' World' + Chalk.bgRed('!'));
log(Chalk.bgBlue('Hello Blue world!'));
log(Chalk.bgGreen('Hello Green world!'));
log(Chalk.bgYellow('Hello Green world!'));

出力結果
bgcolor.png

文字のスタイルを変える

スタイルを変更したい文字列に対して、スタイルの修飾子で囲う

index.js
const Chalk = require('chalk')
const log = console.log;

//文字のスタイル変更
log(Chalk.underline('Hello UnderLine world!'));
log(Chalk.bold('Hello Bold world!'));

出力結果
style.png

文字のスタイルと色を変える

スタイルと色の修飾子を.でつなぐ

index.js
const Chalk = require('chalk')
const log = console.log;

//スタイルと文字の色を変える
log(Chalk.green(
  'I am a green line ' +
  Chalk.blue.underline.bold('with a blue substring') +
  ' that becomes green again!'
));

出力結果
style-color.png

おまけ 公式ページ使用例の出力結果

参考として、公式ページにある使用例の出力結果を載せておきます。

index.js
const chalk = require('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.keyword('orange')('Yay for orange colored text!'));
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
log(chalk.hex('#DEADED').bold('Bold gray!'));

出力結果
sample.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0