实现Nodejs进度条显示

使用方式:

cons ProgressBar = require("./ProgressBar")
const bar = new ProgressBar("当前进度");

function start(index){
  setTimeout(()=>{
    bar.render({completed:index++,total: 100});
    if(index<=100){
      start(index);
    }else{
      bar.clear()
    }
  },10)
}
start(0);

ProgressBar 代码:

// 这里用到一个很实用的 npm 模块,用以在同一行打印文本
const log = require("single-line-log").stdout;

function ProgressBar(description, barLength) {
  this.description = description || "Progress";
  this.length = barLength || 25;

  this.render = function ({ completed, total }) {
    const percent = (completed / total).toFixed(4);
    const cellNum = Math.floor(percent * this.length);

    let cell = "";
    for (let i = 0; i < cellNum; i++) {
      cell += "█";
    }

    let empty = "";
    for (let i = 0; i < this.length - cellNum; i++) {
      empty += "░";
    }

    const value = (100 * percent).toFixed(2);
    const cmdText = `${this.description}: ${value}% ${cell}${empty} ${completed}/${total}`;

    log(cmdText);
  };

  this.clear = () => log("");
}

module.exports = ProgressBar;