3

if console.log is just process.stdout.write with a line-break at the end, then Why do I get nothing printed when I use process.stdout.write but I get answer in console.log() for the following code.

var waittime = 3000;
var currenttime = 0;
var waitint = 10;

function percentage(p) {
    process.stdout.clearLine();
    process.stdout.cursorTo(0);
    process.stdout.write(`waiting ... ${p}%`);
}

var interval = setInterval(function() {
    currenttime += waitint;
    percent = Math.floor((currenttime / waittime) * 100);
    percentage(percent);
}, waitint);

setTimeout(function() {
    clearInterval(interval);
    percentage(100);
    process.stdout.write("\nGowtham");
}, waittime);

process.stdout.write("\nIt's not getting displayed");
//console.log("It's getting displayed here!"); 

What's wrong? There is a difference I guess. Correct me if I'm wrong.

mingos
  • 23,778
  • 12
  • 70
  • 107
Goss Gowtham
  • 100
  • 2
  • 8
  • Possible duplicate of [Difference between "process.stdout.write" and "console.log" in node.js?](https://stackoverflow.com/questions/4976466/difference-between-process-stdout-write-and-console-log-in-node-js) – mingos Mar 08 '18 at 15:15

1 Answers1

4

Please take some time to analyse step by step what process.stdout.* methods are called in your code.

First thing that's called is the last line:

process.stdout.write("\nIt's not getting displayed");

This prints out your message.

Right after that, Node executes the setInterval callback, which contains the percentage() call. There, the first call is:

process.stdout.clearLine();

So your output is printed and immediately removed. console.log() appends a newline character to the output, so the process.stdout.clearLine(); affects an empty line after your message.

If you want your code to work, add a newline to your output string:

process.stdout.write("\nNow it's getting displayed, duh!\n");
mingos
  • 23,778
  • 12
  • 70
  • 107