JagaScript

Logo
1 min read

How to Build a Textual Progress Bar for CLI and Terminal Apps

March 06, 2020
tags: cli, node, terminal

I find textual interfaces extremely interesting and I’m trying to figure out how some common components can be creates

this is the time of a progress bar

gif

to create a textual progress bar we need to understand two simple concepts

  • you can control where the cursor Is programmatically
  • There are ANSI escapes code to cancel the entire screen or the current line (\r)

One way to achieve this is to start a loop and on every iteration print the special escape code \r that will clear the line at the cursor position and then print one of the following to simulate a progress

[.        ]
[..       ]
[...      ]
[....     ]
[.....    ]
[......   ]
[.......  ]
[........ ]
[.........]

In this example, I’ll be using Node.js

async function main() {
  /* using 20 to make the progress bar length 20 charactes, multiplying by 5 below to arrive to 100 */

  for (let i = 0; i <= 20; i++) {
    const dots = ".".repeat(i)
    const left = 20 - i
    const empty = " ".repeat(left)

    /* need to use  `process.stdout.write` becuase console.log print a newline character */
    /* \r clear the current line and then print the other characters making it looks like it refresh*/
    process.stdout.write(`\r[${dots}${empty}] ${i * 5}%`)
    await wait(80)
  }
}

main()

function wait(ms) {
  return new Promise(res => setTimeout(res, ms))
}

This was relatively simple but with some custom colors can have a huge impact in the UX of a tool, especially it takes some time to complete and there is no other feedback for the user that everything is going ok


full code available on the repo on github

Sharing is caring

Blog by Jaga Santagostino.
Software consultant, polyglot developer, maker of things, lifelong learner.
ReactJS Milano & milano.dev organizer