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