103

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 manager.Windows Cmd prompt is being currently used for running nodejs apps.

  1. cls clears the command window or errors in command prompt. Is there a equivalent for node.js ? console.clear does not exist ;( or does it in some other form?

  2. I created a server through this code below

    var http = require("http");
    http.createServer(function (request, response) {
        response.writeHead(200, {
            "Content-Type": "text/html"
        });
        response.write("Hello World");
        console.log("welcome world")response.end();
    }).listen(9000, "127.0.0.1");
    

i changed the code to below and refreshed the browser to find that content type does not change, how do i get to see the changes?

var http = require("http");
http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  console.log("welcome world")
  response.end();
}).listen(9000,"127.0.0.1");
Deeptechtons
  • 10,945
  • 27
  • 96
  • 178

21 Answers21

116
console.log('\033[2J');

This works on linux. Not sure about windows.

You can "trick" the user using something like this:

var lines = process.stdout.getWindowSize()[1];
for(var i = 0; i < lines; i++) {
    console.log('\r\n');
}
sth
  • 222,467
  • 53
  • 283
  • 367
sanatgersappa
  • 4,319
  • 2
  • 18
  • 13
  • Only the second "trick" worked for me, [rest all the answers were useless](http://i.imgur.com/oNIRSMO.png). Using [nodemon](https://github.com/remy/nodemon) on windows8 – laggingreflex Jan 16 '14 at 23:56
  • 11
    in case somebody stubles this. On windows: `process.stdout.write('\033c');`, as `'\033[2J'` only clears current application stream, and `'\033c'` resets std – tenbits Jun 18 '14 at 20:36
  • 24
    This is an [ANSI escape code](http://en.wikipedia.org/wiki/ANSI_escape_code), in case y'all were curious (I was). The `\033` is the octal number of ESC in ASCII. With the bracket it forms the CSI (Control Sequence Introducer). `0J`, `1J`, and `2J` clear top, bottom, and entire screen, respectively. – Jared Beck Nov 09 '14 at 05:08
  • 4
    @TedNyberg You're correct that it won't work in strict mode (octal literal) but you can get around this by using "\x1BC" or "\x1B[EJ" depending on what you need. – Ryan Thomas May 03 '16 at 04:01
  • 1
    @TedNyberg in addition to hex literals (\x...) unicode literals (\u...) such as in Iaktak's answer work as well. – Ryan Thomas May 03 '16 at 04:08
  • 1
    on windows 10 sending special characters failed to prevent scrolling back, but this worked: `require('child_process').execSync('cls', {stdio: 'inherit'});` – bruceceng Dec 18 '20 at 21:59
  • Octal escape sequences not allowed -> change to hex "\x1bc" – l00k May 07 '23 at 21:01
81
process.stdout.write('\033c');

This also works on windows. Win7 at least.

lfree
  • 1,880
  • 3
  • 24
  • 39
56

This clears the console on Windows and puts the cursor at 0,0:

var util = require('util');
util.print("\u001b[2J\u001b[0;0H");

or

process.stdout.write("\u001b[2J\u001b[0;0H");
Community
  • 1
  • 1
laktak
  • 57,064
  • 17
  • 134
  • 164
56

This is for Linux mainly; but is also reported to work in Windows.

There is Ctrl + L in Gnome Terminal that clears the terminal. It can be used with Python, Node JS or any other REPL running in terminal. It has the same effect as clear command.

Nishant
  • 20,354
  • 18
  • 69
  • 101
49

i am using a windows CMD and this worked for me

console.clear();
yousef
  • 1,240
  • 12
  • 13
44

And to clear the console while in strict mode on Windows:

'use strict';
process.stdout.write('\x1Bc'); 
guiweb
  • 965
  • 6
  • 12
21

Starting from Node.JS v8.3.0 you can use method clear:

console.clear()
Alex K
  • 2,613
  • 1
  • 20
  • 31
16

Just use CTRL + L on windows to clear the console.

Lanil Marasinghe
  • 2,785
  • 24
  • 24
8

Haven't tested this on Windows but works on unix. The trick is in the child_process module. Check the documentation. You can save this code as a file and load it to the REPL every time you need it.

var exec = require('child_process').exec;

function clear(){
    exec('clear', function(error, stdout, stderr){
        console.log(stdout);
    });    
}
Abel Terefe
  • 1,440
  • 20
  • 17
6

To solve problems with strict mode:

'use strict';
process.stdout.write('\x1B[2J');
ElGavilan
  • 6,610
  • 16
  • 27
  • 36
Henri Cavalcante
  • 455
  • 5
  • 16
6

Just use the official way:

console.log('Blah blah blah'); // Prints "Blah blah blah"

console.clear(); // Clears, or in other words, resets the terminal.

console.log('You will only see this message. No more Blah blah blah...');
bbkrz
  • 423
  • 1
  • 8
  • 16
3

If you're using VSCode you can use CTRL + K. I know this is not a generic solution but may help some people.

Hexodus
  • 12,361
  • 6
  • 53
  • 72
  • Also works on PHPStorm. `Ctrl+K` looks to be the only solution, when node.js doesn't restore the console on the next run. – bencergazda Aug 01 '18 at 09:07
1

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.

Steven Vachon
  • 3,814
  • 1
  • 30
  • 30
  • Some fun: With `"\u001b[32;1m"` you can set even the color of text (in Windows command line) (- undo code: `"\u001b\x1b[0m"`) more info: http://www.termsys.demon.co.uk/vtansi.htm and http://en.wikipedia.org/wiki/ANSI_escape_code –  Aug 29 '14 at 08:04
1

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);
}
Daemon Beast
  • 2,794
  • 3
  • 12
  • 29
1

On package.json try this:

  "nodemonConfig": {
    "events": {
      "start": "clear"
    }
  }
0

I couldn't get any of the above to work. I'm using nodemon for development and found this the easiest way to clear the console:

  console.log("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

It just scrolls the console several lines so you get a clear screen for subsequent console.log commands.

Hope it helps someone.

ciso
  • 2,887
  • 6
  • 33
  • 58
0

This code works fine on my node.js server console Windows 7.

process.stdout.write("\u001b[0J\u001b[1J\u001b[2J\u001b[0;0H\u001b[0;0W");

SkySibe
  • 153
  • 1
  • 7
0

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

Smartniggs
  • 173
  • 2
  • 5
-1

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

-1

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

Nerdroid
  • 13,398
  • 5
  • 58
  • 69
AmishJohn81
  • 215
  • 1
  • 16
-1

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).

Jean J. Michel
  • 561
  • 1
  • 7
  • 14