Nodejs為終端字符增加樣式
只有黑白的色調對於比較復雜的命令行程序來說就顯得太單調了,我們可以為命令行程序增加樣式使得程序更加友好!
安裝package: npm install -S chalk
#!/bin/env node
const chalk = require('chalk');
const log = console.log;
// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);
const error = chalk.bold.red;
const warning = chalk.keyword('orange');
console.log(error('Error!'));
console.log(warning('Warning!'));
為長時間任務增加進度顯示
progress是當前最流行的用於渲染進度條的npm包。
var ProgressBar = require('progress');
var bar = new ProgressBar(':bar :current/:total', { total: 10 });
var timer = setInterval(function () {
bar.tick();
if (bar.complete) {
clearInterval(timer);
} else if (bar.curr === 5) {
bar.interrupt('this message appears above the progress bar\ncurrent progress is ' + bar.curr + '/' + bar.total);
}
}, 1000);
輸出:
this message appears above the progress bar
current progress is 5/10
========== 10/10