简体   繁体   English

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

[英]Node.Js on windows - How to clear console

Being totally new into node.js environment and philosophy i would like answers to few questions.作为 node.js 环境和哲学的新手,我想回答几个问题。 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.我已经为 windows 安装程序和节点 package 管理器下载了 node.js。Windows Cmd 提示当前正在用于运行 nodejs 应用程序。

  1. cls clears the command window or errors in command prompt. cls 清除命令 window 或命令提示符中的错误。 Is there a equivalent for node.js?是否有 node.js 的等价物? console.clear does not exist;( or does it in some other form? console.clear 不存在;(或者以其他形式存在?

  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");
console.log('\033[2J');

This works on linux.这适用于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');
}
process.stdout.write('\033c');

This also works on windows.这也适用于 Windows。 Win7 at least.至少Win7。

["

This clears the console on Windows and puts the cursor at 0,0:<\/i>这将清除 Windows 上的控制台并将光标置于 0,0:<\/b><\/p>

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

This is for Linux mainly;这主要用于Linux but is also reported to work in Windows.但据报道也可以在 Windows 中工作。

There is Ctrl + L in Gnome Terminal that clears the terminal. Gnome 终端中有Ctrl + L可以清除终端。 It can be used with Python, Node JS or any other REPL running in terminal.它可以与 Python、Node JS 或在终端中运行的任何其他 REPL 一起使用。 It has the same effect as clear command.它与clear命令的效果相同。

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

console.clear();

And to clear the console while in strict mode on Windows:并在 Windows 上处于严格模式时清除控制台:

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

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

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

console.clear()

Haven't tested this on Windows but works on unix.尚未在 Windows 上对此进行测试,但适用于 unix。 The trick is in the child_process module.诀窍在于child_process模块。 Check the documentation.检查文档。 You can save this code as a file and load it to the REPL every time you need it.您可以将此代码保存为文件,并在每次需要时将其加载到 REPL。

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

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

To solve problems with strict mode:使用严格模式解决问题:

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

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

If you're using VSCode you can use CTRL + K .如果您使用的是VSCode ,则可以使用CTRL + K I know this is not a generic solution but may help some people.我知道这不是通用解决方案,但可能会对某些人有所帮助。

Based on sanatgersappa's answer and some other info I found, here's what I've come up with:根据 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);
}

To make things easier , I've released this as an npm package called cli-clear .为了让事情变得更容易,我将它作为一个名为cli-clear的 npm 包发布。

There is no console.clear() in node. 节点中没有console.clear()

With ES6 JavaScript received the ''.repeat() string method , and so we can do: 使用ES6 JavaScript收到了''.repeat()字符串方法 ,因此我们可以这样做:

console.log('\n'.repeat(1000));

which will basically print 1000 empty lines and simulate a console.clear() 这将基本上打印1000个空行并模拟一个console.clear()

You can use the readline module:您可以使用readline模块:

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

readline.clearLine(process.stdout, 0) clears the current line. readline.clearLine(process.stdout, 0)清除当前行。

readline.clearScreenDown(process.stdout) clears everything below the cursor. 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);
}

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:我正在使用 nodemon 进行开发,发现这是清除控制台的最简单方法:

  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.它只是将控制台滚动几行,以便您为后续的 console.log 命令获得清晰的屏幕。

Hope it helps someone.希望它可以帮助某人。

["

此代码在我的 node.js 服务器控制台 Windows 7 上运行良好。<\/p>

process.stdout.write("\\\\\");<\/code><\/p>"]

在 mac 上,我只是简单地使用Cmd + K来清除控制台,非常方便,比在项目中添加代码来做到这一点更好。

Using vs code on Windows, its kinda inconsistent.在 Windows 上使用 vs code,有点不一致。 This is what seems to work for me.这似乎对我有用。

Clear console from package.json script:从 package.json 脚本清除控制台:

(eg 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 (ie vscode's integrated terminal), which is why this works.根据 nodejs 文档,将options.stdio设置为“inherit”会将 stdio stream 传递给父进程(即 vscode 的集成终端),这就是它起作用的原因。

On package.json try this:在 package.json 上试试这个:

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

迟到了,但是如果您使用的是 powershell,则 ctrl+l 可以在 Windows 中使用 :) Powershell + Chocolatey + node + npm = 获胜。

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

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."运行此代码时,您将看到相同的消息“队列测试队列中的消息数:1”。 and the number changing (1..2..3, etc).和数字变化(1..2..3等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM