tus*_*ath 6 javascript console node.js
我想在控制台的两行显示数据.我只是想每次更新两行.
我到现在所做的是 -
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);
Run Code Online (Sandbox Code Playgroud)
此解决方案的明显问题是光标移到窗口的顶部.我不希望这样,它应该显示当前光标所在的内容.可能我需要在我的逻辑中首先获得当前光标位置.有没有办法做到这一点?
替代方案和最优选的解决方案是获得可以执行相同操作的lib
编辑:我已经看到一些关于stackoverflow的问题,它提供了一个没有新行记录的选项,但这不是我想要的.我想要多个非新行记录.
ncurses 是我用来控制终端的最强大的库,mscdex 有一个优秀的 npm 包,它绑定到 c 库https://npmjs.org/package/ncurses
但这对于您的需求来说可能有点矫枉过正,这里有一个替代解决方案,但它涉及使用 bash 脚本:
基于这个要点,我整理了适合您的示例的以下代码,您可以从要点下载它或在此处阅读它,不要忘记向 bash 脚本授予 exec 权限:
chmod +x cursor-position.sh
Run Code Online (Sandbox Code Playgroud)
光标位置.js
module.exports = function(callback) {
require('child_process').exec('./cursor-position.sh', function(error, stdout, stderr){
callback(error, JSON.parse(stdout));
});
}
Run Code Online (Sandbox Code Playgroud)
光标位置.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\}
Run Code Online (Sandbox Code Playgroud)
索引.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);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2029 次 |
| 最近记录: |