cli-progress icon indicating copy to clipboard operation
cli-progress copied to clipboard

How to show progress bar in one line when using for loop ?

Open amrsa1 opened this issue 1 year ago • 3 comments

I have a function where im looping over an array, to do some process this lead to see progress bar appearing in many line rather than show the progress on the same bar.

Could you provide an example how to do so when im using for loop

const bar = new cliProgress.SingleBar({
      format: 'Processing |' + chalk.cyan('{bar}') + '| {percentage}% || {value}/{total} Pages || Current File: {filename}',
      barCompleteChar: '\u2588',
      barIncompleteChar: '\u2591',
      hideCursor: true
    }, cliProgress.Presets.shades_classic);

    bar.start(pages.length, 0, {
      filename: 'Starting...'
    });

    for (const page of pages) {
      const pageName = page.FileLeafRef;

      // Update the progress bar with the current file name and progress
      bar.increment(1, {
        filename: pageName
      });

      const pageContent = page.CanvasContent1;

      if (pageContent) {
        const cleanedContent = cleanHtml(decodedContent);
        const outputPdfPath = `./${path.parse(pageName).name}.pdf`;
        await convertHtmlToPdf(cleanedContent, outputPdfPath);
      } else {
        console.log(chalk.red(`Failed to retrieve content for page: ${pageName}\n`));
      }

amrsa1 avatar Oct 02 '24 14:10 amrsa1

Hi, did you find a fix for this issue? I'm currently running into the same thing. Thanks.

Bryanpablo-GSA avatar Dec 11 '24 17:12 Bryanpablo-GSA

mostly caused by some logs/stdout/stderr writes

AndiDittrich avatar Dec 11 '24 17:12 AndiDittrich

I have successfully used this approach to monkeypatch in logging for SingleBar.

// Initialize progress bar
const bar = new cliProgress.SingleBar({
  format: "🧪 Testing pages [{bar}] {percentage}% | {value}/{total} | ETA: {eta}s | {file}",
});

bar.loggingBuffer = [];
bar.log = function (message) {
  bar.loggingBuffer.push(message);
};
bar.on("redraw-pre", (data) => {
  if (bar.loggingBuffer.length > 0) {
    bar.terminal.clearLine();
    bar.terminal.cursorTo(0);
    while (bar.loggingBuffer.length > 0) {
      bar.terminal.write(bar.loggingBuffer.shift());
      bar.terminal.write("\n");
    }
  }
});

Stole the idea from the current implementation in MultiBar:

https://github.com/npkgz/cli-progress/blob/e2347a35a6c0922cfb0a077cf5ed21696fba46da/lib/multi-bar.js#L246

Also, please note I do not know the best practices for monkey patching so there's probably some obvious improvement possible here.

fulldecent avatar Jun 10 '25 14:06 fulldecent