Created
March 28, 2019 18:29
-
-
Save emrivero/8daefd9d7c6026e2bf0998b5ff7099b2 to your computer and use it in GitHub Desktop.
Console progress Bar in Node.js
This file contains 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
/** | |
* Bar object | |
* @class | |
*/ | |
class Bar { | |
constructor(msg, time) { | |
this.arrBar = new Array(10).fill('.'); | |
this.msg = msg; | |
this.time = time; | |
this.currentTime = 0; | |
} | |
/** | |
* @method | |
*/ | |
update(percentageParam = null) { | |
const percentage = percentageParam || (this.currentTime / this.time) * 100; | |
if (percentage % 10 === 0) { | |
for (let i = 0; i < percentage / 10; i += 1) { | |
this.arrBar[i] = '='; | |
} | |
} | |
this.drawingBar = '[' + this.arrBar.join('') + ']'; | |
return `${this.msg} ${Math.round(percentage)}% ${this.drawingBar}`; | |
} | |
/** | |
* @method | |
*/ | |
start() { | |
this.idTimeout = setInterval(() => { | |
if (this.currentTime < this.time) { | |
process.stdout.clearLine(); | |
process.stdout.cursorTo(0); | |
process.stdout.write(chalk.blue(`${this.update()}`)); | |
this.currentTime += 1; | |
} | |
}, 1000); | |
} | |
/** | |
* @method | |
*/ | |
async stop() { | |
process.stdout.clearLine(); | |
process.stdout.cursorTo(0); | |
process.stdout.write(chalk.blue(`${this.update(100)}\n`)); | |
clearInterval(this.idTimeout); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment