Search code examples
node.jsunicodecommand-line

How to show progress icons in terminal programs like seen here?


I want to write a command-line program that will show UNICODE characters that will "animate" in the left side of a line. How can I do it using node.js to have the checkmark and UNICODE animation you see here in the following image? What are the characters, and how do I make the instructions to overwrite the first character on the line?

Example of the icons


Solution

  • You can build your own spinner in node by writing to stdout like this:

    import { stdout } from "process"
    
    function startSpinner() {
        const characters = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
        const cursorEsc = {
            hide: '\u001B[?25l',
            show: '\u001B[?25h',
        }
        stdout.write(cursorEsc.hide)
    
        let i = 0;
        const timer = setInterval(function () {
            stdout.write("\r" + characters[i++]);
            i = i >= characters.length ? 0 : i;
        }, 150);
    
        return () => {
            clearInterval(timer)
            stdout.write("\r")
            stdout.write(cursorEsc.show)
        }
    }
    

    Then invoke the function like this - here's an example that runs for 4 seconds and then finishes

    const stopSpinner = startSpinner();
    
    setTimeout(() => {
        stopSpinner()
        console.log("done")
    },4000)
    

    Further Reading