Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read ANSI escape from terminal

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.

For example this escape sequence:

CSI 6n | DSR – Device Status Report

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

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.

like image 331
exebook Avatar asked Apr 29 '16 03:04

exebook


People also ask

What is ANSI in terminal?

ANSI escape sequences are a standard for in-band signaling to control cursor location, color, font styling, and other options on video text terminals and terminal emulators. Certain sequences of bytes, most starting with an ASCII escape character and a bracket character, are embedded into text.

Do ANSI escape codes work on Windows?

The Win32 console does not natively support ANSI escape sequences at all. Software such as Ansicon can however act as a wrapper around the standard Win32 console and add support for ANSI escape sequences.


1 Answers

Here's one way:

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

Output:

'\u001b[30;1R'

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.

like image 91
Dogbert Avatar answered Sep 25 '22 07:09

Dogbert