nodejs – 如何保持stdout顶部的状态

我试图输出这样的东西:

counter is: 10 <= fixed line and auto updating console.logs, etc... <= other console.logs, errors, defaul outputs console.logs, etc... console.logs, etc... console.logs, etc... 

这可能吗?

我已经尝试使用process.stdout.write(),但它不工作。

 var counter = 0; setInterval(function(){ counter++; process.stdout.write("counter is " + counter + " \r"); }, 500); setInterval(function(){ console.log('some output'); }, 1500); 

这是一个使用祝福的例子:

 var blessed = require('blessed'); var screen = blessed.screen(), body = blessed.box({ top: 1, left: 0, width: '100%', height: '99%' }), statusbar = blessed.box({ top: 0, left: 0, width: '100%', height: 1, style: { fg: 'white', bg: 'blue' } }); screen.append(statusbar); screen.append(body); screen.key(['escape', 'q', 'C-c'], function(ch, key) { return process.exit(0); }); function status(text) { statusbar.setContent(text); screen.render(); } function log(text) { body.insertLine(0, text); screen.render(); } var c = 1; setInterval(function() { status((new Date()).toISOString()); log('This is line #' + (c++)); }, 100); 

下面是一个简单的例子,它具有几乎相同的效果(状态栏不会用背景颜色填充额外的空间):

 var screen = blessed.screen(), body = blessed.box({ top: 0, left: 0, width: '100%', height: '100%', tags: true }); screen.append(body); screen.key(['escape', 'q', 'C-c'], function(ch, key) { return process.exit(0); }); function status(text) { body.setLine(0, '{blue-bg}' + text + '{/blue-bg}'); screen.render(); } function log(text) { body.insertLine(1, text); screen.render(); } var c = 1; setInterval(function() { status((new Date()).toISOString()); log('This is line #' + (c++)); }, 100); 

一个传统的图书馆做这种事情(在屏幕底部以外的地方绘制文本)是“诅咒”…有Node.js的绑定,但也有“祝福”(哈哈),看起来更容易使用: https : //github.com/chjj/blessed

除了有很多节点模块可以帮助你做到这一点( blessedncursesansitermhelper ),为了教育目的,你也可以使用process.stdout.moveCursor方便地使用vanilla节点:

 var logs = []; function log(text) { logs.push(text); console.log(text); } function changeCounter(n) { process.stdout.moveCursor(0, -logs.length - 1); printCounter(n); logs.forEach(function (log) { console.log(log) }); } function printCounter(n) { console.log('Counter is:', n); } // Now lets test printCounter(0); var i = 1; setInterval(function () { log('meoww'); changeCounter(i++); }); 

虽然你必须写入额外的代码,以防止terminal溢出。