node.js - 如何在 node.js CLI 应用程序中使用日志记录和进度条?

标签 node.js command-line-interface progress-bar winston

上下文

在 Node.js 应用程序中,我使用:

CLI 应用程序将在构建文件时显示进度条。在构建操作期间,有时需要将信息/错误记录到控制台。这扰乱了进度条:

  • 信息/错误在进度条之后立即记录到控制台,而不是换行
  • 在日志完成后再次打印进度条,导致控制台打印多个进度条

控制台说明:

[===========----------------------] 11 / 33 builtwarn: something wrong here.
[=============--------------------] 13 / 33 builtwarn: something wrong here.
warn: example warning that continues here.
error:  some stacktrace
[=================================] 33 / 33 built

问题

有没有办法确保进度条不受干扰,并且控制台的任何信息日志都打印在进度条的上方/下方?这样只显示一个进度条。

我知道有一个 interrupt node-progress 中的方法,但我不确定如何将其与 winston 一起使用。

我认为这在 CLI 应用程序中是一个相当常见的场景,因此也欢迎任何关于如何通过其他依赖项/方法来实现它的建议/想法!

最佳答案

我自己做了一个进度条类。
您可以打印 \r 以清除屏幕上的最后一行。
然后打印你的日志。
之后,打印一个\n,确保新的进度条不会清除你的日志。

class MyProgress {
    constructor(total,str_left,str_right){
        this.str_left=".";
        this.str_right=" ";
        if(str_left)this.str_left=str_left;
        if(str_right)this.str_right=str_right;
        this.total = total;
        this.current=0;
        this.strtotal=60;//progress bar width。
    }
    update(current){
        this.current++;
        if(current)this.current=current;        
        var dots=this.str_left.repeat(parseInt( (this.current % this.total) /this.total*this.strtotal));
        var left = this.strtotal - parseInt( (this.current % this.total) /this.total*this.strtotal);
        var empty = this.str_right.repeat(left);
        process.stdout.write(`\r[${dots}${empty}] ${parseInt(this.current/this.total * 100)}% [${this.total}-${this.current}]`);
        //if(this.total <= this.current){ this.current=0; }//
    }   
}
function print(params,...other){
    process.stdout.write("\r");
    console.log(params,...other);//
    process.stdout.write("\n");
}

关于node.js - 如何在 node.js CLI 应用程序中使用日志记录和进度条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71898650/

相关文章:

javascript - 提取与特定模式匹配的所有值

发生错误时 Hive CLI 选项 -f 不工作

ffmpeg - 如何使用 ffmpeg 将章节添加到 mp4/mkv 文件中?

ios自定义进度条设计

javascript - 异步获取文件夹中的文件?

javascript - 用 Typescript 编写的 React 应用程序中的错误参数类型

javascript - Bootstrap 进度条编程运行时

c# - 进度条 C#

javascript - 如何在 Angular Controller 中使用 Browserified npm 包?

json - aws cli 查询以查找最后拍摄的快照、拍摄日期、使用的标签(如果有)、实例的名称标签和实例 ID