Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to erase the last line of output?

Tags:

A very simple program that prints 3 lines of output:

console.log('a');
console.log('b');
console.log('c');

Is there a way from program to delete the last line after it has been printed?, i.e.

console.log('a');
console.log('b');
console.log('c');
clearLastLine();
console.log('C');

which would produce:

a
b
C
like image 919
Gajus Avatar asked Oct 04 '15 20:10

Gajus


People also ask

What is process stdout?

process. stdout (1): The standard output stream, which is a source of output from the program. process. stderr (2): The standard error stream, which is used for error messages and diagnostics issued by the program.


2 Answers

The simple solution is to not print a newline character (i.e., do not use console.log).

  • Use process.stdout.write to print a line without the EOL character.
  • Use carriage return (\r) character to return to the begin of the line.
  • Use \e[K to clear all characters from the cursor position to the end of the line.

Example:

process.stdout.write("000");
process.stdout.write("\n111");
process.stdout.write("\n222");

To this line, the output will be:

000
111
222

However, if you execute:

process.stdout.write("000");
process.stdout.write("\n111");
process.stdout.write("\n222");
process.stdout.write("\r\x1b[K")
process.stdout.write("333");

The output is:

000
111
222\r\x1b[K
333

However, the terminal will display:

000
111
333
like image 60
Gajus Avatar answered Sep 22 '22 22:09

Gajus


The following works for me:

process.stdout.clearLine();
process.stdout.cursorTo(0); 
like image 37
Richard Nienaber Avatar answered Sep 23 '22 22:09

Richard Nienaber