0

I'm trying to erase the windows console programmatically from a NodeJS script. Not just slide the console output out of view...I want to actually clear it.

I'm writing a tool similar to TypeScript's tsc command, where it will watch a folder and incrementally compile the project. As such, on every file change, I rerun the compiler, and output any errors that are found (one line each). I would like to totally erase the console output so that users are not confused by old error messages as they scroll up the console.

When you run tsc --watch in a directory, TypeScript does exactly what I want. tsc actually erases the entire console output.

I've tried all of the following things:

  • process.stdout.write("\x1Bc");

  • process.stdout.write('\033c')

  • var clear = require('cli-clear'); clear();

  • I tried all of the escape codes from this post.

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

All of these either:

  1. Printed an unknown char to the console

  2. Slid the console down, equivalent to cls, which is NOT what I want.

How do I actually clear the screen and remove ALL of the output? I'm open to using a node module, piping outupt, spawning new cmds, hacks, etc, as long as it gets the job done.

Here's a sample node.js script to test out the issue.

for (var i = 0; i < 15; i++) {
    console.log(i + ' --- ' + i);
}
//clear the console output here somehow
TwitchBronBron
  • 2,783
  • 3
  • 21
  • 45

1 Answers1

0

Adapted from a previous answer. You will need a C compiler (tested with mingw/gcc)

#include <windows.h>

int main(void){
    HANDLE hStdout; 
    CONSOLE_SCREEN_BUFFER_INFO csbiInfo; 
    COORD destinationPoint;
    SMALL_RECT sourceArea;
    CHAR_INFO Fill;

    // Get console handle
    hStdout = CreateFile( "CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0 );

    // Retrieve console information
    if (GetConsoleScreenBufferInfo(hStdout, &csbiInfo)) {
        // Select all the console buffer as source
        sourceArea.Top = 0;
        sourceArea.Left = 0;
        sourceArea.Bottom = csbiInfo.dwSize.Y - 1;
        sourceArea.Right = csbiInfo.dwSize.X - 1;

        // Select a place out of the console to move the buffer
        destinationPoint.X = 0;
        destinationPoint.Y = 0 - csbiInfo.dwSize.Y;

        // Configure fill character and attributes
        Fill.Char.AsciiChar = ' ';
        Fill.Attributes =  csbiInfo.wAttributes;

        // Move all the information out of the console buffer and init the buffer
        ScrollConsoleScreenBuffer( hStdout, &sourceArea, NULL, destinationPoint, &Fill);

        // Position the cursor
        destinationPoint.X = 0;
        destinationPoint.Y = 0;
        SetConsoleCursorPosition( hStdout, destinationPoint );
    }

    return 0;
}

Compiled as clearConsole.exe (or whatever you want), it can be used from node as

const { spawn } = require('child_process');
spawn('clearConsole.exe');
MC ND
  • 69,615
  • 8
  • 84
  • 126