2012-05-15 161 views
4

我遇到了node.js的readline問題。下面顯示的是控制檯輸出:粗體的內容是我輸入的內容,剩下的就是服務器正在記錄的內容。readline with console.log in the background

 
>Teslog message 
>Testinlog message 
> log message 
log message 
Tlog message 
estinglog message 
>123 

簡單地說,我的代碼看起來像這樣

setInterval(function() { console.log("log message") }, 1000); 
var cli = require('readline').createInterface(process.stdin, process.stdout); 
cli.setPrompt("> ", 2); 
cli.on('line', function(line) { 
    cli.prompt(); 
}); 
cli.prompt(); 

我怎樣才能得到及時轉移後得到新的輸出室,而沒有完全搗毀無論我打字?

回答

4

這似乎有點解決了問題 - 在控制檯登錄後至少會重新提示提示。

var log = console.log; 
console.log = function() { 
    // cli.pause(); 
    cli.output.write('\x1b[2K\r'); 
    log.apply(console, Array.prototype.slice.call(arguments)); 
    // cli.resume(); 
    cli._refreshLine(); 
} 

但是,被中斷的提示並未被清除。

編輯:加入cli.output.write('\x1b[2K\r');使工作


編輯2:更完整的解決方案,使得其他像util.log工作,以及:

function fixStdoutFor(cli) { 
    var oldStdout = process.stdout; 
    var newStdout = Object.create(oldStdout); 
    newStdout.write = function() { 
     cli.output.write('\x1b[2K\r'); 
     var result = oldStdout.write.apply(
      this, 
      Array.prototype.slice.call(arguments) 
     ); 
     cli._refreshLine(); 
     return result; 
    } 
    process.__defineGetter__('stdout', function() { return newStdout; }); 
} 

#EDIT 3 :看起來像cli.pause()cli.resume() before and af呼叫是多餘的。

+0

你有沒有顯示那些「更多黑客」?你應該顯示什麼做了,沒有像你想要的那樣工作。 – jcolebrand

+0

是的,第4行被說成是黑客 – Eric

+1

但是請讓人們明白什麼沒有工作和做什麼,這就是我所要求的。 – jcolebrand