如何更新多行控制台上的数据

我想在控制台的两行显示数据。 我只是想每次更新这两行。

我到现在为止所做的是 –

var _logInline = function(alpha, bravo) { process.stdout.cursorTo(0, 0); process.stdout.clearLine(); process.stdout.cursorTo(0); process.stdout.write(alpha.toString()); process.stdout.write('\n'); process.stdout.clearLine(); process.stdout.cursorTo(0); process.stdout.write(bravo.toString()); process.stdout.write('\n'); }; var delay = 1000; var time = 0; setInterval(function() { time++; _logInline('alpha-' + time, 'bravo-' + time * time); }, delay); 

这个解决scheme的明显问题是光标移到窗口的顶部。 我不希望这样,而是应该显示光标所在的位置。 可能我需要首先在我的逻辑中获取当前的光标位置。 有没有办法做到这一点?

替代和最优选的解决scheme将获得一个lib可以做同样的事情

编辑:我已经看到了一些问题,它提供了一个没有新行的日志选项,但这不是我想要的。 我想要多个没有新的在线logging。

ncurses是我用来控制terminal的function最强大的库,有一个很好的npm包,由mscdex绑定到c库https://npmjs.org/package/ncurses

但是可能对您的需求来说是一点点矫枉过正,下面是一个替代解决scheme,但它涉及到使用bash脚本:

基于这个要点,我把下面的代码放在一起,你可以从gist中下载它,或者在这里阅读它,不要忘了给bash脚本赋予exec权限:

  chmod +x cursor-position.sh 

光标position.js

 module.exports = function(callback) { require('child_process').exec('./cursor-position.sh', function(error, stdout, stderr){ callback(error, JSON.parse(stdout)); }); } 

cursor-position.sh

 #!/bin/bash # based on a script from http://invisible-island.net/xterm/xterm.faq.html # http://stackoverflow.com/questions/2575037/how-to-get-the-cursor-position-in-bash exec < /dev/tty oldstty=$(stty -g) stty raw -echo min 0 # on my system, the following line can be replaced by the line below it echo -en "\033[6n" > /dev/tty # tput u7 > /dev/tty # when TERM=xterm (and relatives) IFS=';' read -r -d R -a pos stty $oldstty # change from one-based to zero based so they work with: tput cup $row $col row=$((${pos[0]:2} - 1)) # strip off the esc-[ col=$((${pos[1]} - 1)) echo \{\"row\":$row,\"column\":$col\} 

index.js

 var getCursorPosition = require('./cursor-position'); var _logInline = function(row, msg) { if(row >= 0) row --; //litle correction process.stdout.cursorTo(0, row); process.stdout.clearLine(); process.stdout.cursorTo(0, row); process.stdout.write(msg.toString()); }; var delay = 1000; var time = 0; //Start by getting the current position getCursorPosition(function(error, init) { setInterval(function() { time++; _logInline(init.row, 'alpha-' + time); _logInline(init.row + 1, 'bravo-' + time * time); }, delay); });