清除NodeJS流中的所有行

问题描述 投票:3回答:4

process.stdout.clearLine()删除最新行。如何删除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);

输出为:

1
3
4

我想从stdout中删除所有行而不是最新行,所以输出将是:

3
4
node.js stream
4个回答
9
投票

不知道这是否有助于您尝试以下代码:

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
投票

您也可以尝试这个; process.stdout.write('\u001B[2J\u001B[0;0f');与在命令行上发出clear命令具有相同的效果!也许有帮助!


2
投票

请尝试:-

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)

0
投票

下面的print函数可以带任意多个换行符的字符串:

function print(input) {
  const numberOfLines = (input.match(/\n/g) || []).length;
  process.stdout.clearScreenDown();
  process.stdout.write(input);
  process.stdout.cursorTo(0);
  process.stdout.moveCursor(0, -numberOfLines);
}

您可以尝试以下方式:

// the following will print out different line lengths
setInterval(() => {
  if (Math.random() > 0.7) {
    print(`Hey ${Date.now()}

    I hope you are having a good time! ${Date.now()}

    Bye ${Date.now()}`);
  } else if (Math.random() > 0.3) {
    print(`Hello ${Date.now()}

    Good bye ${Date.now()}`);
  } else {
    print(`just one line ${Date.now()}`);
  }
}, 1000);
© www.soinside.com 2019 - 2024. All rights reserved.