Kory
Kory

Reputation: 1446

How do I update values in a node console app in real time?

I have the following code:

let counter = 0;
function printProgress(){
    // process.stdout.write('\x1B[2J\x1B[0f');
    console.log("Count is: " + counter);
    counter++;
}

setInterval(function(){
  printProgress();
}, 1000)

Which produces output like this:

Count is: 0
Count is: 1
Count is: 2
etc...

Uncommenting...

process.stdout.write('\x1B[2J\x1B[0f');

...clears the screen and gives the appearance of updating the counter value (sort of what I want but not really). Instead of clearing the screen every time, how do I actually update/display the counter value in real time?

Upvotes: 0

Views: 2582

Answers (3)

kirosc
kirosc

Reputation: 174

Use log-update

const logUpdate = require('log-update');

const frames = ['-', '\\', '|', '/'];
let i = 0;

setInterval(() => {
    const frame = frames[i = ++i % frames.length];

    logUpdate(
`
        ♥♥
   ${frame} unicorns ${frame}
        ♥♥
`
    );
}, 80);

Upvotes: 3

Sandesh K
Sandesh K

Reputation: 929

Try using jetty:

var Jetty = require("jetty");

var jetty = new Jetty(process.stdout);

jetty.clear();


let counter = 0;
function printProgress(){
  jetty.moveTo([0, 7]).text(counter.toString())
  counter++;
}

jetty.text("count: 0")
setInterval(function(){
  printProgress()
}, 1000)

Additionally, you can do many different things on your console using Jetty. It supports different colors, formatting and styles.

Upvotes: 0

Hemant Rajpoot
Hemant Rajpoot

Reputation: 690

here is try it

let counter = 0;
function printProgress() {
  process.stdout.clearLine();
  process.stdout.cursorTo(0);
  process.stdout.write('Count is: ' + counter);
  counter++;
}

setInterval(function() {
  printProgress();
}, 1000);

Upvotes: 2

Related Questions