How to erase characters printed in console


Question

I've been searching how to do it in other languages and I've found that I have to use the special character \b to remove the last character. (how-do-i-erase-printed-characters-in-a-console-applicationlinux)

This doesn't work for node.js in multiple calls to console.log ();

If I write a single log:

console.log ("abc\bd");

I get the result: abd

But if I write:

console.log ("abc");
console.log ("\bd");

I get the result:

abc
d

My goal is to print a waiting message like:

Waiting
Waiting.
Waiting..
Waiting...

and again:

Waiting
Waiting.
etc

all in the same line.

1
66
5/23/2017 11:54:19 AM

Accepted Answer

There are functions available for process.stdout:

var i = 0;  // dots counter
setInterval(function() {
  process.stdout.clearLine();  // clear current text
  process.stdout.cursorTo(0);  // move cursor to beginning of line
  i = (i + 1) % 4;
  var dots = new Array(i + 1).join(".");
  process.stdout.write("Waiting" + dots);  // write text
}, 300);

Update Dec 13, 2015: although the above code works, it is no longer documented as part of process.stdin. It has moved to readline

122
12/13/2015 10:35:35 AM

Now you could use readline library and its API to do this stuff.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon