2012-07-22 55 views
52

我一直在搜索如何在其他語言中執行此操作,並且我發現必須使用特殊字符\ b刪除最後一個字符。 (how-do-i-erase-printed-characters-in-a-console-applicationlinux如何清除控制檯中打印的字符

這對多次調用console.log()中的node.js不起作用。

如果我寫了一個日誌:

console.log ("abc\bd"); 

我得到的結果是:ABD

但如果我寫:

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

我得到的結果是:

ABC
d

我的目標是打印等待消息,如:

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

,並再次:

等待
等待。
etc

全部在同一行。

回答

97

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

更新 2015年12月13日:雖然上面的代碼工作,它不再被記錄爲的process.stdin一部分。它已經移動到readline

+1

我想到的是,引擎蓋下的「\ r」字符啓用此。該字符將光標返回到行的開頭,而不開始換行。 – 2013-07-26 03:41:17

+0

不是在Windows上。 – 2014-03-13 14:33:07

+6

@pimvdb這些功能在哪裏記錄?它們似乎不在Node文檔中:http://nodejs.org/api/process.html#process_process_stdout – 2014-06-19 20:55:56

17

現在你應該使用require('readline')和它的API做這個東西。

+0

不配一個lib'require' – fedeghe 2018-03-01 14:46:12

9

覆蓋同一行的最簡單方法是

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

\r是關鍵。它會將光標移回行的開頭。

+5

'\ r'的唯一問題是它不會清除當前行。所以如果你第一次寫「abcdefg \ r」,下一次你會用「zyxwefg」寫下「zyxw \ r」。 – docksteaderluke 2015-10-01 12:14:59

+0

這是真的,但在這種情況下,你應該總是寫一個比以前更長的線。 – jonnysamps 2015-10-02 23:06:54

+4

不在OP的情況下。 – docksteaderluke 2015-10-03 02:14:14

-3

嘗試通過在字符串的開頭移動\ R,這個工作在Windows上對我來說:

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

這將不起作用 - 'console.log'在字符串的末尾添加一個'\ n'。你需要使用'process.stdout.write' – Sethi 2017-01-27 11:03:53