1

I've been working on some problems on projecteuler.net, and am programming functions and algorithms to solve these problems in mostly JavaScript (ran in the Node.js environment).

In many of these problems I am going through many thousand different numbers, and I would like to show (in the terminal output) which number it is currently on. I don't want it to just keep writing new lines, but just update the existing line... Is there a way to do this in JavaScript? Possibly with the help of any Node modules?

I know there is a way to clear the console, and so I could just have it clear it and then write the number again, but that would also clear the previous output that I still want to show...

Thanks in advance!

1
  • Look into ANSI escape codes if you want to do this by hand, or look into one of the many Node.js libraries. Search keyword is ANSI escape codes Commented Jul 25, 2021 at 4:10

1 Answer 1

1

May be this suffices?

import readline from 'readline';

function clearLine() {
  readline.cursorTo(process.stdout, 0);
  readline.clearLine(process.stdout, 0);
}

let counter = 0;

setInterval(() => {
  clearLine();
  process.stdout.write(String(counter++));
}, 1000);
Sign up to request clarification or add additional context in comments.

3 Comments

It seems to work how I want it... One question... do you know what the average execution time of that is?
@JacobHornbeck Sorry, I do not(
Okay, that's fine. Thank you for your answer, it does help a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.