Tom
Tom

Reputation: 5121

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

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?

Upvotes: 2

Views: 1004

Answers (2)

Sumedh Rao
Sumedh Rao

Reputation: 3

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.

Upvotes: 0

Bartosh Lenart
Bartosh Lenart

Reputation: 31

Please check if this works for You. final solutions after edit:

let lines = process.stdout.rows

// Clear console
process.stdout.write('\x1Bc');
var stop = false;
for (var i = 0; i < lines; i++) {
  if (i === 0) {
    console.log(1);
  } else if (i === Math.round(lines / 4)) {
    console.log('halfwayish');
  } else if (i === lines/2) {
    stop = true;
    console.log('end');
  } else if(stop === false){
    console.log('\r\n');
  }
}

Upvotes: 1

Related Questions