Node.Js on windows - How to clear console

前端 未结 19 1424
迷失自我
迷失自我 2020-12-02 08:51

Being totally new into node.js environment and philosophy i would like answers to few questions. I had downloaded the node.js for windows installer and also node package man

相关标签:
19条回答
  • 2020-12-02 09:25

    In my case I did it to loop for ever and show in the console a number ever in a single line:

    class Status {
    
      private numberOfMessagesInTheQueue: number;
      private queueName: string;
    
      public constructor() {
        this.queueName = "Test Queue";
        this.numberOfMessagesInTheQueue = 0;
        this.main();
      }
    
      private async main(): Promise<any> {    
        while(true) {
          this.numberOfMessagesInTheQueue++;
          await new Promise((resolve) => {
            setTimeout(_ => resolve(this.showResults(this.numberOfMessagesInTheQueue)), 1500);
          });
        }
      }
    
      private showResults(numberOfMessagesInTheQuee: number): void {
        console.clear();
        console.log(`Number of messages in the queue ${this.queueName}: ${numberOfMessagesInTheQuee}.`)
      }
    }
    
    export default new Status();
    

    When you run this code you will see the same message "Number of messages in the queue Test Queue: 1." and the number changing (1..2..3, etc).

    0 讨论(0)
  • 2020-12-02 09:26

    You can use the readline module:

    readline.cursorTo(process.stdout, 0, 0) moves the cursor to (0, 0).

    readline.clearLine(process.stdout, 0) clears the current line.

    readline.clearScreenDown(process.stdout) clears everything below the cursor.

    const READLINE = require('readline');
    
    function clear() {
        READLINE.cursorTo(process.stdout, 0, 0);
        READLINE.clearLine(process.stdout, 0);
        READLINE.clearScreenDown(process.stdout);
    }
    
    0 讨论(0)
  • 2020-12-02 09:31

    Based on sanatgersappa's answer and some other info I found, here's what I've come up with:

    function clear() {
        var stdout = "";
    
        if (process.platform.indexOf("win") != 0) {
            stdout += "\033[2J";
        } else {
            var lines = process.stdout.getWindowSize()[1];
    
            for (var i=0; i<lines; i++) {
                stdout += "\r\n";
            }
        }
    
        // Reset cursur
        stdout += "\033[0f";
    
        process.stdout.write(stdout);
    }
    

    To make things easier, I've released this as an npm package called cli-clear.

    0 讨论(0)
  • 2020-12-02 09:31

    On mac, I simply use Cmd + K to clear the console, very handy and better than adding codes inside your project to do it.

    0 讨论(0)
  • 2020-12-02 09:32

    Belated, but ctrl+l works in windows if you're using powershell :) Powershell + chocolatey + node + npm = winning.

    0 讨论(0)
  • 2020-12-02 09:32

    Ctrl + L This is the best, simplest and most effective option.

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