上下文
在 Node.js 应用程序中,我使用:
- node-progress进度条
- winston用于记录
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/