Skip to content

Instantly share code, notes, and snippets.

@quentinlamamy
Last active July 3, 2024 14:31
Show Gist options
  • Save quentinlamamy/86800893d5d23046caf835fea80954a9 to your computer and use it in GitHub Desktop.
Save quentinlamamy/86800893d5d23046caf835fea80954a9 to your computer and use it in GitHub Desktop.
[NodeJs] Progress Bar (Use of ANSI escape sequence to refresh)
/**
* Display a progress bar in the console
* @description The progress bar self update without clearing the console (using ANSI escape codes)
* @author Quentin Lamamy <contact@quentin-lamamy.fr>
* @param {Number} current - Current value
* @param {Number} total - Total value
* @param {String} title - Title of the progress bar
* @param {String} message - Message to display
* @returns {void}
*/
function displayProgressBar(current, total, title = "",message = "") {
if (current > 0) console.log("\x1b[3A")
const barSize = 50;
const barPercent = Math.round(current / total * 100);
const barCurrent = Math.round(barSize * current / total);
console.log(`${title} [${'='.repeat(barCurrent)}${' '.repeat(barSize - barCurrent)}] ${barPercent}% (${current}/${total})`)
console.log(message)
}
/*
Usage Example
*/
let total = 100;
let current = 0;
let interval = setInterval(() => {
if (current !== total) {
displayProgressBar(current, total,"My step name","Loading file " + current.toString());
current++;
} else {
clearInterval(interval);
}
}, 1000);
/*
_._ _,-'""`-._
(,-.`._,'( |\`-/|
`-.-' \ )-`( , o o)
`- \`_`"'- I am runnig after any code challenge, please feed me
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment