Getting the visible number of rows (or height) of the terminal in Node.js

Viewed 506

Looking at the TTY node module, I can access process.stdout.rows which returns "A number specifying the number of rows the TTY currently has." But obviously the available ones and not the visible ones as the following code:

let lines = process.stdout.rows

// Clear console
process.stdout.write('\x1Bc')

for (var i = 0; i < lines; i++) {
  if (i === 0) {
    console.log(1)
  } else if (i === Math.round(lines / 2)) {
    console.log('halfwayish')
  } else if (i === lines - 1) {
    console.log('end')
  } else {
    console.log('\r\n')
  }
}

outputs:

enter image description here

How can I make it so that end is at the end, halfwayish is halfwayish and 1 is at the first line without having to scroll in the terminal?

2 Answers

for me this worked. Basically take out the newlines

process.stdout.on('resize', () => {
 process.stdout.write('\x1Bc')
 var lines = process.stdout.rows
 for (var i = 0; i < lines; i++) {
    if (i === 0) {
        console.log(1)
    } else if (i === Math.round(lines / 2)) {
        console.log('halfwayish')
    } else if (i === lines - 1) {
        console.log('end')
    } else {
        console.log("")
    }
 }
});

I think the console.log itself adds a new line, and you adding another new line is making it go beyond what the lines variable has.

Related