Last active
July 19, 2017 19:47
-
-
Save scwood/f56baf16b20c7a3088f3f755473e4c4e to your computer and use it in GitHub Desktop.
Progress bar in 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 readline = require('readline') | |
| function drawProgress(current, total, promptLength = 25) { | |
| const percentComplete = current / total | |
| const visualPercent = Math.round(percentComplete * 100) | |
| const inProgressLength = Math.round(promptLength * percentComplete) | |
| const filledBar = rightPad('='.repeat(inProgressLength), ' ', promptLength) | |
| readline.cursorTo(process.stdout, 0) | |
| process.stdout.write(`[${filledBar}] ${visualPercent}%`) | |
| } | |
| function rightPad (str, char, length) { | |
| return (str.toString() + char.repeat(length)).substr(0, length) | |
| } | |
| let progress = 0 | |
| const timer = setInterval(() => { | |
| progress++ | |
| drawProgress(progress, 100) | |
| if (progress === 100) { | |
| clearInterval(timer) | |
| console.log() | |
| } | |
| }, 10) | |
| // $ node progress.js | |
| // [=========================] 100% |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment