Gajus Gajus - 3 years ago 171
Node.js Question

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

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');
eraseLastLine();
console.log('C');


which would produce:

a
b
C

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download