Last active
December 20, 2024 14:05
-
-
Save pete-otaqui/bfc4e251161c0ca07c98790ccdd4be23 to your computer and use it in GitHub Desktop.
Live progress log line for node CLI apps
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
function lpad(numOrStr, size) { | |
let s = `${numOrStr}`; | |
while (s.length < size) { | |
s = ` ${s}`; | |
} | |
return s; | |
} | |
/** | |
* Live progress log on a single shell line. | |
* Outputs a live line in the console like: | |
* ` 24 / 2345 (1%)` | |
* | |
* Usage: | |
* ```js | |
* console.log("starting"); | |
* for (let i = 0; i < 1000; i += Math.random() * 10) { | |
* logProgress(i, 1000); | |
* } | |
* console.log(""); // to start a new line in the shell | |
* ``` | |
*/ | |
export function logProgress(count, total) { | |
const padSize = total.toString().length; | |
const percent = Math.round(100 * count / total); | |
// Create a padded count string like ` 1` or `1234` | |
const countText = lpad(count, padSize) | |
// Create a padded percent string like: ` (2%)`, ` (12%)` or `(100%)` | |
const percentText = lpad(`(${percent}%)`, 6); | |
process.stdout.clearLine(-1); | |
process.stdout.cursorTo(0); | |
process.stdout.write(`${countText} / ${total} ${percentText}`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment