如何清除控制台中打印的字符


76

我一直在寻找其他语言的用法,但发现必须使用特殊字符\ b删除最后一个字符。(如何在控制台应用程序Linux中擦除打印的字符

对于多次调用console.log()的node.js,这不起作用。

如果我写一个日志:

console.log ("abc\bd");

我得到结果:abd

但是如果我写:

console.log ("abc");
console.log ("\bd");

我得到结果:

abc
d

我的目标是打印一条等待消息,例如:

等待
等待。
等待中..
等待中...

然后再次:

等待
等待。
等等

都在同一行。

Answers:


131

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

可以提供参数 clearLine(direction, callback)

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

2015年12月13日更新:尽管以上代码有效,但不再作为的一部分进行记录process.stdin。它已移至readline


1
我希望引擎盖下的'\ r'字符能够启用此功能。该字符将光标返回到行的开头,而无需开始新行。
Casey Watson

不在Windows上。
Adam K Dean

7
@pimvdb这些功能记录在哪里?它们似乎不在Node文档中:nodejs.org/api/process.html#process_process_stdout
Henry Merriam

5
这似乎在OSX上不起作用,有人知道是否应该这样做吗?
Znarkus 2014年

1
API可能已更改。这个答案是两年前写的,任何JS开发人员至少应该对过去两年中发生的变化有一些了解。我们已经从几种编译为JS的语言(最著名的是CoffeeScript)转变为转译即将发布的最新版本(即将发布)ES6。两年前,如果我没记错的话,ES6模块甚至不存在。
伊赛亚·梅多斯


17

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

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

\r是关键。它将光标移回该行的开头。


8
'\ r'的唯一问题是它不会清除当前行。因此,如果您第一次写“ abcdefg \ r”,而下一次写“ zyxw \ r”,则最终会得到“ zyxwefg”。
2015年

没错,但是在这种情况下,您应该总是比以前写更长的行。
jonnysamps,2015年

8
并非在OP的情况下。
2015年


0

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

为我工作(仅使用单个字符进行测试)


回车不正确,因为它会抹掉整行。如果将其替换为\b答案,它将起作用。另外,请确保更新您的示例,以便阅读该示例的人可以立即理解您的示例(在这里,我想知道:为什么不尝试删除一个字符以证明其工作正常?)
aymericbeaumet

-3

尝试通过在字符串的开头移动\ r,这在Windows上对我有效:

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

1
这将不起作用-在字符串的末尾console.log添加a \n。您需要使用process.stdout.write
Sethi
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.