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
答案 0 :(得分:7)
不知道这是否有助于您尝试此代码:
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);
答案 1 :(得分:1)
你也可以尝试这个; process.stdout.write('\u001B[2J\u001B[0;0f');
这与在命令行上发出clear
命令具有相同的效果!也许这有帮助!
答案 2 :(得分:1)
试试这个: -
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)
答案 3 :(得分: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);