122

我的node.js应用程序有很多控制台日志,这对我来说很重要(这是一个相当大的应用程序,所以运行了很长时间,我需要知道事情仍在进行中)但我最终得到了数千行控制台日志。

是否有可能以某种方式console.update擦除/替换控制台行而不是创建新行?

4

8 回答 8

156

尝试在控制台上使用 process.stdout 方法:

process.stdout.write("Hello, World");
process.stdout.clearLine(0);
process.stdout.cursorTo(0);
process.stdout.write("\n"); // end the line

TypeScript:clearLine()将 -1、0 或 1 作为方向参数,含义如下:

-1:光标左侧。
0:整行。
1 - 从光标向右

于 2016-06-01T06:38:24.323 回答
79

按照@michelek 的回答,您可以使用类似这样的函数:

function printProgress(progress){
    process.stdout.clearLine();
    process.stdout.cursorTo(0);
    process.stdout.write(progress + '%');
}
于 2016-12-28T04:33:11.440 回答
31

当然,您可以使用我帮助创建的模块来执行此操作:fknsrs/jetty

通过安装

npm install jetty

这是一个使用示例

// Yeah, Jetty!
var Jetty = require("jetty");

// Create a new Jetty object. This is a through stream with some additional
// methods on it. Additionally, connect it to process.stdout
var jetty = new Jetty(process.stdout);

// Clear the screen
jetty.clear();

// write something
jetty.text("hello world");
jetty.moveTo([0,0]);
jetty.text("hello panda");

Jetty 在单独使用时并不是很有用。当您在它之上构建一些抽象以使您的码头调用不那么冗长时,它会更有效。

于 2013-06-26T01:13:36.087 回答
22

只需使用 \r 终止您的线路:

process.stdout.write('text\r');

这是一个简单的例子(挂钟):

setInterval(() => process.stdout.write(`clock: ${new Date()}\r`), 1000);
于 2020-05-29T13:03:08.283 回答
16

写部分行。

process.stdout.write('text');
process.stdout.write('more');
process.stdout.write('\n'); // end the line

如果输出量是真正的问题,那么您可能会重新考虑您的日志记录。您可以使用允许选择性运行时日志记录的日志记录系统,以将输出范围缩小到您需要的范围。

// The sections we want to log and the minimum level
var LOG_LEVEL = 4;
var LOG_SECTIONS = ['section1', 'section2', 'section3'];

function logit(msg, section, level) {
  if (LOG_SECTIONS.includes(section) && LOG_LEVEL >= level) {
    console.log(section + ':' + msg);
  }
}

logit('message 1', 'section1', 4); // will log
logit('message 2', 'section2', 4); // will log
logit('message 3', 'section3', 2); // wont log, below log level
logit('message 4', 'section4', 4); // wont log, not in a log section
于 2013-06-26T00:50:17.463 回答
6

TypeError: process.stdout.clearLine is not a function如果您在 Visual Studio Code(或 Webstorm)的调试控制台窗口中看到 stdout 异常,请将应用程序作为外部终端应用程序而不是内部控制台运行。原因是调试控制台窗口不是 TTY(process.stdout.isTTY为假)。launch.json因此使用"console": "externalTerminal"选项更新您的启动配置。

于 2019-04-28T17:49:33.897 回答
4

我们可以使用日志更新

const logUpdate = require('log-update');
logUpdate('this will be gone');
logUpdate('this will stay');
于 2021-09-11T11:53:30.183 回答
0

其中,@michelek 的回答可以解决问题。但是,当您开始使用它时,当输出被重定向到文件或者您在调试器中或在 linux 屏幕会话中运行等时,您可能会遇到异常问题。您可能会看到诸如process.stdout.clearLine is not a function.

因此,至少添加一个测试以检查输出是否为“TTY”并且能够执行“clearLine()”和“cursorTo()”之类的操作:

if (process.stdout.isTTY) {
   process.stdout.write("Hello, World");
   process.stdout.clearLine(0);
   process.stdout.cursorTo(0);
   process.stdout.write("\n"); // end the line
}
于 2022-02-22T12:56:47.350 回答