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

Yon*_*ong 6 command-line-interface node.js winston progress-bar

语境

在 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
Run Code Online (Sandbox Code Playgroud)

问题

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

我知道节点进度中有一种interrupt方法,但我不确定如何与温斯顿一起使用它。

我想这在 CLI 应用程序中是一个相当常见的场景,因此任何关于如何通过其他依赖项/方法来做到这一点的建议/想法也值得赞赏!

小智 1

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

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