はじめに
Nodeでコマンドプロンプトの出力(console.log)に色をつけたかったので、その方法を投稿します。
検索してもwebブラウザのconsoleに色を付ける方法が多くヒットしたので、私と同じように困っている人の助けになれば…(こんなことで困ってないか
)。
結論
色を付けるnpm がありました!!
chalk
npm i chalk
前提条件
環境
- node
v10.16.3 - npm
6.9.0
使用例
ざっくりと使用例と出力結果を投稿します。
全ての例を投稿するわけではないので詳しく見たい方はchalkのページで確認してください。
色を変える
色を変えたい文字列を、変えたい色の修飾子で囲う
※変えられる色の種類はchalkのページで確認してください。
index.js
constChalk=require('chalk')constlog=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!'));背景色を変える
色を変えるのとほぼ変わらない。
index.js
constChalk=require('chalk')constlog=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!'));文字のスタイルを変える
スタイルを変更したい文字列に対して、スタイルの修飾子で囲う
index.js
constChalk=require('chalk')constlog=console.log;//文字のスタイル変更log(Chalk.underline('Hello UnderLine world!'));log(Chalk.bold('Hello Bold world!'));文字のスタイルと色を変える
スタイルと色の修飾子を.でつなぐ
index.js
constChalk=require('chalk')constlog=console.log;//スタイルと文字の色を変えるlog(Chalk.green('I am a green line '+Chalk.blue.underline.bold('with a blue substring')+' that becomes green again!'));おまけ 公式ページ使用例の出力結果
参考として、公式ページにある使用例の出力結果を載せておきます。
index.js
constchalk=require('chalk');constlog=console.log;// Combine styled and normal stringslog(chalk.blue('Hello')+' World'+chalk.red('!'));// Compose multiple styles using the chainable APIlog(chalk.blue.bgRed.bold('Hello world!'));// Pass in multiple argumentslog(chalk.blue('Hello','World!','Foo','bar','biz','baz'));// Nest styleslog(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 literallog(`
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!'));



