Dams_al
Dams_al

Reputation: 71

Refreshing data in terminal (nodejs)

I work on a small project, just "simple":

An user can write on terminal, crypto currencies like this :

yarn start btc eth

and I display an array some data (Price, Change 24 etc...), I use:

I can do this, now I want refresh this array X seconds... but I don't know how do it :/ (I tried with setInterval bad idea hahaha) , I use only nodejs and express for my server but I think I have to do use socketIO no ?

Upvotes: 0

Views: 518

Answers (1)

Dominik
Dominik

Reputation: 6313

To refresh data in the terminal (cli) you have to use ANSI escape codes. I've been doing that for a while now so I created a small gist for myself to keep track of all the things you can do with them: https://gist.github.com/dominikwilkowski/60eed2ea722183769d586c76f22098dd

An example below:

process.stdout.write('This line will be deleted');
process.stdout.write('\u001b[2K' + '\u001b[1G');
// \u001b[2K = clear line
// \u001b[1G = reset cursor to start of line
process.stdout.write('This line will replace above line');
process.stdout.write('\n');

So you can do that with your table. You either know how many lines your table is and place your cursor to that sport and clear the rest and redraw the table or you clear the screen entirely each time. I would suggest the former.

Your use-case might be something like this:

let draw = 0;
function drawTable() {
  draw ++;
  process.stdout.write(` your \n table \n data ${draw} \n`); // prints 3 lines
}

drawTable(); // initial draw
const myInterval = setInterval(() => {
  process.stdout.write('\u001b[3A\u001b[1G');
  // move three rows up and reset cursor to first column
  drawTable(); // draw again
}, 1000); // redraw your table every second

This will increment your output and clearing it in between draws.

Upvotes: 2

Related Questions