7

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

到现在为止我所做的是——

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);

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

替代和最优选的解决方案是获得一个可以做同样事情的库

编辑:我在 stackoverflow 上看到了一些问题,这些问题提供了在没有换行的情况下进行日志记录的选项,但这并不是我想要的。我想要多个无换行记录。

4

2 回答 2

1

ncurses 是我用来控制终端的最强大的库,mscdex 有一个优秀的 npm 包,它绑定到 c 库https://npmjs.org/package/ncurses

但这对于您的需求可能有点过头了,这是一个替代解决方案,但它涉及使用 bash 脚本:

基于这个要点,我整理了以下适用于您的示例的代码,您可以从要点下载或在此处阅读,不要忘记为 bash 脚本授予 exec 权限:

  chmod +x cursor-position.sh 

光标位置.js

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

光标位置.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);
});
于 2013-12-04T18:21:17.527 回答
0

想了很久才做这个。。。

这是多行的一个非常天真的解决方案:


import {execSync} from "child_process";

var util = require('util');
var x = 0;
var y = 100;
setInterval(function () {
    execSync('tput cuu1 tput el tput cuu1 tput el', {stdio: 'inherit'});
    process.stdout.write(`hello1: ${x++}\nhello2: ${y++}\r`);  // needs return '/r'
    // util.print('hello: ' + x + '\r');  // could use this too
}, 1000);

当我有更强大的实现时,我会更新。

于 2019-04-06T23:12:07.647 回答