Created
December 8, 2018 14:23
-
-
Save Foair/b176b8651901ee6887fe7ad033d83c19 to your computer and use it in GitHub Desktop.
Node 控制台进度条
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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