node.js 如何擦除控制台中打印的字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11600890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:03:24  来源:igfitidea点击:

How to erase characters printed in console

node.js

提问by Gabriel Llamas

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

这对多次调用 console.log() 的 node.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.

都在同一行。

回答by pimvdb

There are functions available for process.stdout:

有以下功能可用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);

It is possible to provide arguments to clearLine(direction, callback)

可以提供论据 clearLine(direction, callback)

/**
 * -1 - to the left from cursor
 *  0 - the entire line // default
 *  1 - to the right from cursor
 */

UpdateDec 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

回答by Sergey Kamardin

Now you could use readlinelibrary and its APIto do this stuff.

现在你可以使用readline库和它的API来做这些事情。

回答by jonnysamps

The easiest way to overwrite the same line is

覆盖同一行的最简单方法是

var dots = ...
process.stdout.write('Progress: '+dots+'\r');

the \ris the key. It will move the cursor back to the beginning of the line.

\r是关键。它会将光标移回行首。

回答by Michael Yurin

This works for me:

这对我有用:

process.stdout.write('3c');
process.stdout.write('Your text here');

回答by Lolo

process.stdout.write("\r");

Worked for me (only tested with single character)

对我来说有效(仅用单个字符测试)

回答by daremkd

Try by moving the \r at the start of the string, this worked on Windows for me:

尝试在字符串的开头移动 \r,这对我来说适用于 Windows:

for (var i = 0; i < 10000; i+=1) {
    setTimeout(function() {
        console.log(`\r ${i}`);
    }, i);
}