Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js process.stdout.write is flickering in a for loop

I am making a console interface, and using a for loop.

for (let i = 0; i < 100000; i++) {
  process.stdout.clearLine();
  process.stdout.cursorTo(0);
  process.stdout.write('Something: ' + i);
}

when I use this, the 'Something: i' flickers. Is there any way to make it not flicker?

EDIT: I am using the windows command prompt, is there a way to prevent the flickering there?

like image 586
Ank i zle Avatar asked Sep 08 '25 11:09

Ank i zle


1 Answers

You were sooo close! So the flicker is happening because you are clearing the whole line, You need to just clear the stream(in your case STDOUT) from right side of your cursor.

According to the doc:

process.stdout.clearLine(1);

This will do the trick.

Full code from your example:

for (let i = 0; i < 100000; i++) {
  process.stdout.clearLine(1);// <<--here
  process.stdout.cursorTo(0);
  process.stdout.write('Something: ' + i);
}
like image 166
Aritra Chakraborty Avatar answered Sep 11 '25 03:09

Aritra Chakraborty