Windows 上的 Node.Js-如何清除控制台

作为 node.js 环境和哲学的全新领域,我想回答一些问题。我已经下载了 node.js 用于 Windows Installer 和 node 包管理器。WindowsCmd 提示符目前用于运行 nodejs 应用程序。

  1. Cls 清除命令窗口或命令提示符中的错误。是否存在与 node.js 等价的东西?Clear 不存在; (或者它以其他形式存在?)?

  2. 我通过下面的代码创建了一个服务器

    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");
115650 次浏览
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');
}

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);
});
}

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");

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.

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.

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.

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

This also works on windows. Win7 at least.

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

To solve problems with strict mode:

'use strict';
process.stdout.write('\x1B[2J');

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

'use strict';
process.stdout.write('\x1Bc');

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

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

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");

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

i am using a windows CMD and this worked for me

console.clear();

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

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);
}

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

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

console.clear()

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

Using vs code on Windows, its kinda inconsistent. This is what seems to work for me.

Clear console from package.json script:

(e.g. before executing your app)

{
"scripts": {
"clear": "node -e \"process.stdout.write('\\033c')\""
}
}

In a file, clear the console up to the start of the script:

(Not super helpful for comparing deep logs)

console.clear()

completely obliterate all evidence of previous attempts at programming:

import { execSync } from child_process
execSync(process.platform === 'win32' ? 'cls' : 'clear', { stdio: 'inherit' })

according to the nodejs docs, setting options.stdio to 'inherit' passes the stdio stream to the parent process (i.e. vscode's integrated terminal), which is why this works.

On package.json try this:

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