【问题标题】:How to completely erase the console output in windows?如何完全擦除 Windows 中的控制台输出?
【发布时间】:2019-02-19 12:09:20
【问题描述】:

我正在尝试以编程方式从 NodeJS 脚本中删除 Windows 控制台。不仅仅是将控制台输出滑出视野......我想真正清除它。

我正在编写一个类似于 TypeScript 的tsc 命令的工具,它将监视一个文件夹并逐步编译项目。因此,在每次文件更改时,我都会重新运行编译器,并输出发现的任何错误(每行一行)。我想完全清除控制台输出,以便用户在向上滚动控制台时不会被旧的错误消息弄糊涂。

当您在目录中运行 tsc --watch 时,TypeScript 完全符合我的要求。 tsc 实际上会擦除整个控制台输出。

我已经尝试了以下所有方法:

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

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

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

  • 我尝试了来自this post的所有转义码。

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

所有这些:

  1. 向控制台打印一个未知字符

  2. 向下滑动控制台,相当于cls,这不是我想要的。

我如何真正清除屏幕并删除所有输出?我愿意使用节点模块、管道输出、产生新的 cmd、hack 等,只要它能完成工作。

这是一个用于测试问题的示例 node.js 脚本。

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

【问题讨论】:

  • 试试 process.stdout.write("\u001b[2J\u001b[0;0H");
  • @NikolaLukic,这是否包含 Windows 10 控制台的转义序列(早期 Windows 版本不支持)?

标签: node.js typescript cmd terminal


【解决方案1】:

改编自previous answer。您将需要一个 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');

【讨论】:

    猜你喜欢
    • 2013-03-05
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 2015-02-06
    • 2014-09-04
    相关资源
    最近更新 更多