Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to erase characters printed in console

Tags:

node.js

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.

like image 884
Gabriel Llamas Avatar asked Jul 22 '12 13:07

Gabriel Llamas


People also ask

How to backspace in console?

"\b" is ASCII backspace. Print it to back up one char. Thanks, this works perfectly.

How do you delete a printed character in C++?

Try backspace \b or erase the whole line and print it again. Show activity on this post. Show activity on this post.

How do you clear a single line in C++?

(using \r)

How do you erase a character in computer?

The Correct Answer is Backspace button. The Backspace key or Backspace key is a keyboard key that deletes any character before the cursor's current position or the left.


2 Answers

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); 

It is possible to provide arguments to clearLine(direction, callback)

/**  * -1 - to the left from cursor  *  0 - the entire line // default  *  1 - to the right from cursor  */ 

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

like image 101
pimvdb Avatar answered Oct 13 '22 05:10

pimvdb


The easiest way to overwrite the same line is

var dots = ... process.stdout.write('Progress: '+dots+'\r'); 

the \r is the key. It will move the cursor back to the beginning of the line.

like image 39
jonnysamps Avatar answered Oct 13 '22 04:10

jonnysamps