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

发布于 2024-12-29 02:53:57 字数 792 浏览 3 评论 0原文

作为 Node.js 环境和哲学的新手,我想知道几个问题的答案。我已经下载了 Windows 安装程序的 Node.js 以及节点包管理器。Windows Cmd 提示符当前用于运行 NodeJS 应用程序。

  1. cls 清除命令窗口或命令提示符中的错误。 node.js 是否有等效项? console.clear 不存在 ;( 或者以其他形式存在?

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

    var http = require("http");
    http.createServer(函数(请求,响应){
        响应.writeHead(200, {
            “内容类型”:“文本/html”
        });
        响应.write(“你好世界”);
        console.log("欢迎世界")response.end();
    }).listen(9000, "127.0.0.1");
    

我将代码更改为下面并刷新浏览器发现内容类型没有改变,我如何才能看到更改?

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

Being totally new into node.js environment and philosophy i would like answers to few questions. I had downloaded the node.js for windows installer and also node package manager.Windows Cmd prompt is being currently used for running nodejs apps.

  1. cls clears the command window or errors in command prompt. Is there a equivalent for node.js ? console.clear does not exist ;( or does it in some other form?

  2. I created a server through this code below

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

绿光 2025-01-05 02:53:57
console.log('\033[2J');

这适用于 Linux。不确定窗户。

您可以使用如下方式“欺骗”用户:

var lines = process.stdout.getWindowSize()[1];
for(var i = 0; i < lines; i++) {
    console.log('\r\n');
}
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');
}
裸钻 2025-01-05 02:53:57
process.stdout.write('\x1Bc')

跨平台:适用于 Linux、Windows 7/10/11、Mac
不留换行符
清除回滚

\x1B (或 \033 使用已弃用的八进制文字表示同一字符)是 ASCII 转义字符

此行为与 cls 命令相同在 Windows 上,clear 命令在 Linux/Mac 上

process.stdout.write('\x1Bc')

Cross-platform: works on Linux, Windows 7/10/11, Mac
Doesn't leave a newline
Clears scrollback

\x1B (or \033 which uses deprecated octal literal for the same character) is ASCII Escape character

This behavior is identical to cls command on Windows and clear command on Linux/Mac

旧时浪漫 2025-01-05 02:53:57

这主要针对Linux;但据报道也可以在 Windows 中工作。

Gnome 终端中有 Ctrl + L 可以清除终端。它可以与 Python、Node JS 或在终端中运行的任何其他 REPL 一起使用。它与clear命令具有相同的效果。

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.

蹲墙角沉默 2025-01-05 02:53:57

这将清除 Windows 上的控制台并将光标置于 0,0:

var util = require('util');
util.print("\u001b[2J\u001b[0;0H");

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

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");
嘦怹 2025-01-05 02:53:57

我正在使用 Windows CMD,这对我有用

console.clear();

i am using a windows CMD and this worked for me

console.clear();
╄→承喏 2025-01-05 02:53:57

在 Windows 上处于严格模式时清除控制台:

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

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

'use strict';
process.stdout.write('\x1Bc'); 
智商已欠费 2025-01-05 02:53:57

从 Node.JS v8.3.0 开始,您可以使用方法 clear

console.clear()

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

console.clear()
水水月牙 2025-01-05 02:53:57

只需在 Windows 上使用 CTRL + L 即可清除控制台。

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

酷炫老祖宗 2025-01-05 02:53:57

尚未在 Windows 上测试过,但可以在 UNIX 上运行。诀窍在于 child_process 模块。检查文档。您可以将此代码保存为文件,并在每次需要时将其加载到 REPL。

var exec = require('child_process').exec;

function clear(){
    exec('clear', function(error, stdout, stderr){
        console.log(stdout);
    });    
}

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);
    });    
}
无声静候 2025-01-05 02:53:57

使用严格模式解决问题:

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

To solve problems with strict mode:

'use strict';
process.stdout.write('\x1B[2J');
自演自醉 2025-01-05 02:53:57

使用官方的方式即可:

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

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

旧时模样 2025-01-05 02:53:57

如果您使用 VSCode,则可以使用 CTRL + K。我知道这不是通用解决方案,但可能会对某些人有所帮助。

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

梦与时光遇 2025-01-05 02:53:57

根据 sanatgersappa 的回答和我发现的其他一些信息,我得出以下结论:

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

为了让事情变得更容易,我将其作为一个名为 cli-clear

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.

山有枢 2025-01-05 02:53:57

您可以使用readline模块:

readline.cursorTo(process.stdout, 0, 0)将光标移动到(0, 0)。

readline.clearLine(process.stdout, 0) 清除当前行。

readline.clearScreenDown(process.stdout) 清除光标下方的所有内容。

const READLINE = require('readline');

function clear() {
    READLINE.cursorTo(process.stdout, 0, 0);
    READLINE.clearLine(process.stdout, 0);
    READLINE.clearScreenDown(process.stdout);
}

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);
}
花开雨落又逢春i 2025-01-05 02:53:57

在 package.json 上尝试以下操作:

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

On package.json try this:

  "nodemonConfig": {
    "events": {
      "start": "clear"
    }
  }
执着的年纪 2025-01-05 02:53:57

我无法让上述任何一个工作。我正在使用 nodemon 进行开发,发现这是清除控制台的最简单方法:

  console.log("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

它只需滚动控制台几行,这样您就可以获得后续 console.log 命令的清晰屏幕。

希望它能帮助某人。

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.

痴情 2025-01-05 02:53:57

此代码在我的 Node.js 服务器控制台 Windows 7 上运行良好。

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

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

假面具 2025-01-05 02:53:57

在 Mac 上,我只需使用 Cmd + K 来清除控制台,非常方便,并且比在项目中添加代码来执行此操作更好。

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

っ〆星空下的拥抱 2025-01-05 02:53:57

这段代码对我来说效果很好

console.log("\x1bc")

This code works fine for me

console.log("\x1bc")
一桥轻雨一伞开 2025-01-05 02:53:57

只是为这个问题添加一个解决方案。

我发现这个 gist 并且该解决方案对我有用,在视窗。

只是这样:

process.stdout.write("\u001Bc\u001B[3J");

Just to add one more solution to this problem.

I found this gist and the solution works for me, on Windows.

Just this:

process.stdout.write("\u001Bc\u001B[3J");
蒗幽 2025-01-05 02:53:57

迟来了,但如果你使用 powershell,ctrl+l 可以在 Windows 中使用:) Powershell + Chocolatey + Node + npm = 获胜。

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

南汐寒笙箫 2025-01-05 02:53:57

Ctrl + L 这是最好、最简单、最有效的选项。

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

情丝乱 2025-01-05 02:53:57

就我而言,我这样做是为了永远循环,并在控制台中在一行中显示一个数字:

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

当您运行此代码时,您将看到相同的消息“队列测试队列中的消息数:1”。以及数字的变化(1..2..3等)。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文