3

I can determine the terminal window size with process.stdout.columns, process.stdout.rows, and can recalculate my positioning with the resize event.

I am struggling to find out how to get my current cursor position for doing something like updating a specific location on my terminal, then returning to the previous location.

Does Node offer something like process.stdeout.x, process.stdeout.y to tell me where I currently am?

I realise I there are some Linux specific work arounds, but is there something offered by Node that allows for this functionality in a cross platform way?

David Alsh
  • 6,747
  • 6
  • 34
  • 60
  • 1
    Do you use the "readline" built in module? It has a line event & cursor property: https://nodejs.org/dist/latest-v16.x/docs/api/readline.html AND of course a `getCursorPos()` method. – Marc Nov 25 '21 at 13:32

1 Answers1

1

The position returned by readline is relative to the current cursor location, not absolute on the screen.

I was able to create a promise to get this information using the answer below containing the escape sequence for requesting terminal cursor position:

How can I get position of cursor in terminal?

const getCursorPos = () => new Promise((resolve) => {
    const termcodes = { cursorGetPosition: '\u001b[6n' };

    process.stdin.setEncoding('utf8');
    process.stdin.setRawMode(true);

    const readfx = function () {
        const buf = process.stdin.read();
        const str = JSON.stringify(buf); // "\u001b[9;1R"
        const regex = /\[(.*)/g;
        const xy = regex.exec(str)[0].replace(/\[|R"/g, '').split(';');
        const pos = { rows: xy[0], cols: xy[1] };
        process.stdin.setRawMode(false);
        resolve(pos);
    }

    process.stdin.once('readable', readfx);
    process.stdout.write(termcodes.cursorGetPosition);
})

const AppMain = async function () {
    process.stdout.write('HELLO');
    const pos = await getCursorPos();
    process.stdout.write("\n");
    console.log({ pos });
}

AppMain();
DAC
  • 346
  • 1
  • 3
  • 10