I've been searching how to do it in other languages and I've found that I have to use the special character \b to remove the last character. (how-do-i-erase-printed-characters-in-a-console-applicationlinux)
我一直在寻找如何在其他语言中使用它,我发现我必须使用特殊字符\b来删除最后一个字符。(how-do-i-erase-printed-characters-in-a-console-applicationlinux)
This doesn't work for node.js in multiple calls to console.log ();
对于节点来说,这是行不通的。js多次调用控制台。日志();
If I write a single log:
如果我写一个日志:
console.log ("abc\bd");
I get the result: abd
结果是abd
But if I write:
但如果我写:
console.log ("abc");
console.log ("\bd");
I get the result:
我得到的结果:
abc
d
abc d
My goal is to print a waiting message like:
我的目标是打印一条等待的消息,比如:
Waiting
Waiting.
Waiting..
Waiting...
等待等待。等待. .等待……
and again:
再一次:
Waiting
Waiting.
etc
等待等待。等
all in the same line.
都在同一条线上。
4 个解决方案
#1
104
There are functions available for process.stdout
:
有一些用于处理的函数。
var i = 0; // dots counter
setInterval(function() {
process.stdout.clearLine(); // clear current text
process.stdout.cursorTo(0); // move cursor to beginning of line
i = (i + 1) % 4;
var dots = new Array(i + 1).join(".");
process.stdout.write("Waiting" + dots); // write text
}, 300);
Update Dec 13, 2015: although the above code works, it is no longer documented as part of process.stdin
. It has moved to readline
更新2015年12月13日:尽管上述代码有效,但它不再作为process.stdin的一部分被文档化。它已经移动到readline
#2
#3
10
The easiest way to overwrite the same line is
重写同一行最简单的方法是
var dots = ...
process.stdout.write('Progress: '+dots+'\r');
the \r
is the key. It will move the cursor back to the beginning of the line.
r是关键。它将把光标移回行首。
#4
-3
Try by moving the \r at the start of the string, this worked on Windows for me:
试着在弦的开始处移动\r,这对我来说是很有效的:
for (var i = 0; i < 10000; i+=1) {
setTimeout(function() {
console.log(`\r ${i}`);
}, i);
}
#1
104
There are functions available for process.stdout
:
有一些用于处理的函数。
var i = 0; // dots counter
setInterval(function() {
process.stdout.clearLine(); // clear current text
process.stdout.cursorTo(0); // move cursor to beginning of line
i = (i + 1) % 4;
var dots = new Array(i + 1).join(".");
process.stdout.write("Waiting" + dots); // write text
}, 300);
Update Dec 13, 2015: although the above code works, it is no longer documented as part of process.stdin
. It has moved to readline
更新2015年12月13日:尽管上述代码有效,但它不再作为process.stdin的一部分被文档化。它已经移动到readline
#2
#3
10
The easiest way to overwrite the same line is
重写同一行最简单的方法是
var dots = ...
process.stdout.write('Progress: '+dots+'\r');
the \r
is the key. It will move the cursor back to the beginning of the line.
r是关键。它将把光标移回行首。
#4
-3
Try by moving the \r at the start of the string, this worked on Windows for me:
试着在弦的开始处移动\r,这对我来说是很有效的:
for (var i = 0; i < 10000; i+=1) {
setTimeout(function() {
console.log(`\r ${i}`);
}, i);
}