簡體   English   中英

清除 NodeJS 流中的所有行

[英]Clear all lines in NodeJS stream

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

不知道這是否有助於您嘗試此代碼:

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

嘗試這個:-

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)

你也可以試試這個; process.stdout.write('\\'); 這與在命令行上發出clear命令具有相同的效果! 也許這有幫助!

下面的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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM