如何在Windows中完全删除控制台输出?
我试图从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");
所有这些都是:
- 在控制台上打印一个未知的字符
- 滑下控制台,相当于
cls
,这不是我想要的。
如何清除屏幕并删除所有输出?我愿意使用节点模块,管道输出,产生新的cmds,黑客等,只要它完成工作。
这是一个示例node.js脚本来测试问题。
for (var i = 0; i < 15; i++) {
console.log(i + ' --- ' + i);
}
//clear the console output here somehow
回答如下:
改编自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');