簡體   English   中英

如何完全清除Windows中的控制台輸出?

[英]How to completely erase the console output in windows?

我正在嘗試通過NodeJS腳本以編程方式擦除Windows控制台。 不僅僅是將控制台輸出滑出視線...我實際上想清除它。

我正在編寫一個與TypeScript的tsc命令類似的工具,該工具將監視一個文件夾並逐步編譯該項目。 這樣,每次更改文件時,我都會重新運行編譯器,並輸出發現的錯誤(每行一行)。 我想完全擦除控制台輸出,以便用戶在向上滾動控制台時不會被舊的錯誤消息所迷惑。

當您在目錄中運行tsc --watch時,TypeScript完全可以執行我想要的操作。 tsc實際上會擦除整個控制台輸出。

我已經嘗試了以下所有操作:

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

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

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

  • 我嘗試了這篇文章中的所有轉義代碼。

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

所有這些:

  1. 將未知字符輸出到控制台

  2. 向下滑動控制台,相當於cls ,這不是我想要的。

我實際上如何清除屏幕並刪除所有輸出? 我願意使用節點模塊,管道輸出,產生新的cmds,hacks等,只要它能完成工作即可。

這是一個示例node.js腳本,用於測試問題。

for (var i = 0; i < 15; i++) {
    console.log(i + ' --- ' + i);
}
//clear the console output here somehow

改編自先前的答案 您將需要一個C編譯器(已通過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;
}

編譯為clearConsole.exe (或任何您想要的文件),可以從節點使用它作為

const { spawn } = require('child_process');
spawn('clearConsole.exe');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM