Skip to content

Instantly share code, notes, and snippets.

@Foair
Created December 8, 2018 14:23
Show Gist options
  • Save Foair/b176b8651901ee6887fe7ad033d83c19 to your computer and use it in GitHub Desktop.
Save Foair/b176b8651901ee6887fe7ad033d83c19 to your computer and use it in GitHub Desktop.
Node 控制台进度条
const ProgressBar = require('./progress-bar');
const pb = new ProgressBar('下载进度', 50);
let num = 0,
total = 200;
function download() {
if (num <= total) {
pb.render({ completed: num, total });
++num;
setTimeout(download, 100);
}
}
download();
const slog = require('single-line-log').stdout;
class ProgressBar {
constructor(describtion = 'Progress', length = 25) {
this.describtion = describtion;
this.length = length;
}
render(opts) {
const percent = (opts.completed / opts.total).toFixed(4);
const cellNum = Math.floor(percent * this.length);
let cell = '';
for (let i = 0; i < cellNum; ++i) cell += '█';
let empty = '';
for (let i = 0; i < this.length - cellNum; ++i) empty += '░';
const cmdText = `${this.describtion}: ${(100 * percent).toFixed(
2
)}% ${cell}${empty}`;
slog(cmdText);
}
}
module.exports = ProgressBar;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment