Build Command-Line Spinners in Node.js

Practice your Node.js-terminal skills by building your own CLI spinners

In my last post, we saw how to implement a progress bar in the terminal using Nodejs. Here, we will continue with the CLI streak and implement spinners in the terminal using Nodejs.

The Concept

The question is how do we make something like Material Design, Bootstrap progress-bars in a terminal. It seems impossible but it could be done.

In my previous article, we know that the terminal is divided into cells in an x-y plane like a graph with x and y-axis.

It starts with (x, y) (0, 0) in a positive plane. The terminal by default starts at 0, 0 i.e the cursor is placed at 0, 0 . The cursor current position determines where data will be written to next.

If we place the cursor at (x, y) (9, 5) , data will start from the (x, y) (9, 5) position. And this can be done with the readline API readline#cursorTo(stdout, int x: Number, int y: Number) in Nodejs.

Now, we have this knowledge.

To have a spinning line effect like this:

We know to spin a line, we start with this - , then anticlockwise, we have \ , then | and last / . Then we start again from - to / . Now if we can do the above pretty quickly we will have a spinning effect in our terminal.

- \ | /

So all we have to do is to write - , \ , | , / in the same cell rapidly.

To do this in JavaScript, first, we will hold the - , \ , | , / in an array. We will set up an index variable to hold the current index position in the array. Then we will set up a time interval with the setInterval API.

We will give a time of 100ms, this is to make it execute the function callback very fast to achieve the spinning effect. The function callback will retrieve the current line type from the array using the index we declared previously. Then we write the line type with the process.stdout.write API. Using this API will make the cursor to advance to the next cell, no we don't want that. So, we use the readline#cursorTo API to set the cursor back to the previous cell, so on the next call, the next line type in the array will be written to the same cell.

So with all these executing at speed 100ms, we will see the spinning effect.

Tip: Easily reuse small modules across your JS projects

Use Bit to easily develop, isolate and publish small modules in your different projects. Don’t install entire libraries and don’t copy-paste code, when you can build faster with small reusable modules. Take a look.

Ramda components: Just collect and reuse components in your projects to build faster

Making the spinner in Nodejs