从终端读取 ANSI 转义 [英] Read ANSI escape from terminal

查看:28
本文介绍了从终端读取 ANSI 转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

维基百科文章关于终端 ANSI 转义码显示了一些可以发送到一个终端 AND 然后一些数据返回给应用程序.请举例说明如何发送代码,然后在 Node.js 应用程序中读取结果.

Wikipedia article on terminal ANSI escape codes shows some codes that could be sent to a terminal AND then some data is returned back to the application. Please provide an example how to send the code and then read the result in Node.js application.

例如这个转义序列:

CSI 6n |DSR – 设备状态报告

CSI 6n | DSR – Device Status Report

将光标位置 (CPR) 报告给应用程序(就像在键盘上输入一样)ESC[n;mR,其中 n 是行,m 是列.)

Reports the cursor position (CPR) to the application as (as though typed at the keyboard) ESC[n;mR, where n is the row and m is the column.)

我花了几个小时尝试使用 process.stdoutprocess.stdin、各种 fs.* 函数,甚至尝试从 /dev/tty 读取.一切都白费了,完全迷路了.

I spent hours trying to use process.stdout, process.stdin, various fs.* functions, even tried to read from /dev/tty. All in vain, got totally lost.

推荐答案

这是一种方法:

var util = require("util");

function dsr(callback) {
  process.stdin.setRawMode(true);
  process.stdin.once("data", function(data) {
    process.stdin.setRawMode(false);
    process.stdin.pause();
    callback(data.toString());
  });
  process.stdout.write("\x1b[6n");
}

dsr(function(data) {
  console.log(util.inspect(data));
});

输出:

'\u001b[30;1R'

我让 stdin 进入原始模式,这样结果就不会打印在终端中,并且无需用户按回车键即可读取结果.

I'm making stdin go into raw mode so that the result is not printed in the terminal and can be read without the user having to press return.

这篇关于从终端读取 ANSI 转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆