How to erase characters printed in console

前端 未结 6 1129
被撕碎了的回忆
被撕碎了的回忆 2020-12-22 19:03

I\'ve been searching how to do it in other languages and I\'ve found that I have to use the special character \\b to remove the last character. (how-do-i-erase-printed-chara

相关标签:
6条回答
  • 2020-12-22 19:09

    The easiest way to overwrite the same line is

    var dots = ...
    process.stdout.write('Progress: '+dots+'\r');
    

    the \r is the key. It will move the cursor back to the beginning of the line.

    0 讨论(0)
  • 2020-12-22 19:16

    There are functions available for process.stdout:

    var i = 0;  // dots counter
    setInterval(function() {
      process.stdout.clearLine();  // clear current text
      process.stdout.cursorTo(0);  // move cursor to beginning of line
      i = (i + 1) % 4;
      var dots = new Array(i + 1).join(".");
      process.stdout.write("Waiting" + dots);  // write text
    }, 300);
    

    It is possible to provide arguments to clearLine(direction, callback)

    /**
     * -1 - to the left from cursor
     *  0 - the entire line // default
     *  1 - to the right from cursor
     */
    

    Update Dec 13, 2015: although the above code works, it is no longer documented as part of process.stdin. It has moved to readline

    0 讨论(0)
  • 2020-12-22 19:22

    This works for me:

    process.stdout.write('\033c');
    process.stdout.write('Your text here');
    
    0 讨论(0)
  • 2020-12-22 19:22

    Try by moving the \r at the start of the string, this worked on Windows for me:

    for (var i = 0; i < 10000; i+=1) {
        setTimeout(function() {
            console.log(`\r ${i}`);
        }, i);
    }
    
    0 讨论(0)
  • 2020-12-22 19:28

    Using a Carriage Return

    The carriage return character places the cursor back at the beginning of the current line.

    process.stdout.write("\r");
    

    This solution worked for me — I only tested it with a single character.

    0 讨论(0)
  • 2020-12-22 19:32

    Now you could use readline library and its API to do this stuff.

    0 讨论(0)
提交回复
热议问题