Clear all lines in NodeJS stream

2019-05-29 11:02发布

问题:

process.stdout.clearLine() deletes latest line. How can I delete all lines from stdout?

var out = process.stdout;
out.write("1\n"); // prints `1` and new line
out.write("2");   // prints `2`

setTimeout(function () {
    process.stdout.clearLine(); // clears the latest line (`2`)
    out.cursorTo(0);            // moves the cursor at the beginning of line
    out.write("3");             // prints `3`
    out.write("\n4");           // prints new line and `4`
    console.log();
}, 1000);

The output is:

1
3
4

I want to delete all lines from stdout instead of latest line, so the output will be:

3
4

回答1:

dont know if this helps you try this code:

var out = process.stdout;
var numOfLinesToClear = 0;
out.write("1\n");   // prints `1` and new line
++numOfLinesToClear;
out.write("2\n");
++numOfLinesToClear;
process.stdout.moveCursor(0,-numOfLinesToClear); //move the cursor to first line
setTimeout(function () {   
    process.stdout.clearLine();
    out.cursorTo(0);            // moves the cursor at the beginning of line
    out.write("3");             // prints `3`
    out.write("\n4");           // prints new line and `4`
    console.log();
}, 1000);


回答2:

You can try this one also; process.stdout.write('\u001B[2J\u001B[0;0f'); this has the same effect of issuing the clear command on the command line! Maybe that helps!



回答3:

try this:-

var x = 1, y = 2;
process.stdout.write(++x + "\n" + (++y))
function status() {
  process.stdout.moveCursor(0, -2)      // moving two lines up
  process.stdout.cursorTo(0)            // then getting cursor at the begining of the line
  process.stdout.clearScreenDown()      // clearing whatever is next or down to cursor
  process.stdout.write(++x + "\n" + (++y))
}

setInterval(status, 1000)