2012-05-15 164 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