Santos
Santos

Reputation: 434

Node js console write percentage

I need to write in the same line with other lines going at the same time.

var i = 1;
write();
function write() {
    if (i == 6) return;
    setTimeout(function() {
        console.log('-------------');
        process.stdout.write('Downloading ' + i + '% complete... \r');
        i++;
        write();
    }, 100);
}

What I get:

-------------
-------------% complete... 
-------------% complete... 
-------------% complete...  Downloading 5% complete...

What I need:

-------------
Downloading 5% complete...
-------------
-------------
-------------
-------------

I prefer to do this without any modules.

There are various topics here talking about this, but none explains how to do as I want.

I think I need to save the cursor position when I write the line the first time and then the next time I write, I have to move the cursor to the saved line right?

Upvotes: 2

Views: 4971

Answers (2)

Aaron Dufour
Aaron Dufour

Reputation: 17505

process.stdout.write('Downloading ' + i + '% complete... \r');

The \r character means to return to the beginning of the current line. You're looking for \n, which also jumps down a line. Or just continue to use console.log as for your other line, which automatically appends a newline.

Upvotes: 4

Rajkumar Madhuram
Rajkumar Madhuram

Reputation: 684

I have done this kind of thing using the curses library in C/C++. There is a node equivalent called node-ncurses which might help you.

https://github.com/mscdex/node-ncurses

Upvotes: 0

Related Questions