Repository files navigation

Build Status

Single Bar | Multi Bar | Options | Examples | Presets | Events

CLI-Progress

easy to use progress-bar for command-line/terminal applications

Demo

Demo

Install

$ yarn add cli-progress
$ npm install cli-progress --save

Features

  • Simple, Robust and Easy to use
  • Full customizable output format (various placeholders are available)
  • Single progressbar mode
  • Multi progessbar mode
  • Custom Bar Characters
  • FPS limiter
  • ETA calculation based on elapsed time
  • Custom Tokens to display additional data (payload) within the bar
  • TTY and NOTTY mode
  • No callbacks required - designed as pure, external controlled UI widget
  • Works in Asynchronous and Synchronous tasks
  • Preset/Theme support
  • Custom bar formatters (via callback)
  • Logging during multibar operation

Usage

Multiple examples are available e.g. example.js - just try it $ node example.js

constcliProgress=require('cli-progress');// create a new progress bar instance and use shades_classic themeconstbar1=newcliProgress.SingleBar({},cliProgress.Presets.shades_classic);// start the progress bar with a total value of 200 and start value of 0bar1.start(200,0);// update the current value in your application..bar1.update(100);// stop the progress barbar1.stop();

Single Bar Mode

Demo

Example

constcliProgress=require('cli-progress');// note: you have to install this dependency manually since it's not required by cli-progressconstcolors=require('ansi-colors');// create new progress barconstb1=newcliProgress.SingleBar({format: 'CLI Progress |'+colors.cyan('{bar}')+'| {percentage}% || {value}/{total} Chunks || Speed: {speed}',barCompleteChar: '\u2588',barIncompleteChar: '\u2591',hideCursor: true});// initialize the bar - defining payload token "speed" with the default value "N/A"b1.start(200,0,{speed: "N/A"});// update valuesb1.increment();b1.update(20);// stop the barb1.stop();

Constructor

Initialize a new Progress bar. An instance can be used multiple times! it's not required to re-create it!

constcliProgress=require('cli-progress');const<instance> = new cliProgress.SingleBar(options:object [, preset:object]);

Options

::start()

Starts the progress bar and set the total and initial value

<instance>.start(totalValue:int, startValue:int [, payload:object = {}]);

::update()

Sets the current progress value and optionally the payload with values of custom tokens as a second parameter. To update payload only, set currentValue to null.

<instance>.update([currentValue:int [, payload:object = {}]]);
// update progress without altering value
<instance>.update([payload:object = {}]);

::increment()

Increases the current progress value by a specified amount (default +1). Update payload optionally

<instance>.increment([delta:int [, payload:object = {}]]);
// delta=1 assumed
<instance>.increment(payload:object = {}]);

::setTotal()

Sets the total progress value while progressbar is active. Especially useful handling dynamic tasks.

<instance>.setTotal(totalValue:int);

::stop()

Stops the progress bar and go to next line

<instance>.stop();

::updateETA()

Force eta calculation update (long running processes) without altering the progress values.

Note: you may want to increase etaBuffer size - otherwise it can cause INF eta values in case the value didn't changed within the time series.

<instance>.updateETA();

Multi Bar Mode

Demo

Example

constcliProgress=require('cli-progress');// create new containerconstmultibar=newcliProgress.MultiBar({clearOnComplete: false,hideCursor: true,format: ' {bar} | {filename} | {value}/{total}',},cliProgress.Presets.shades_grey);// add barsconstb1=multibar.create(200,0);constb2=multibar.create(1000,0);// control barsb1.increment();b2.update(20,{filename: "test1.txt"});b1.update(20,{filename: "helloworld.txt"});// stop all barsmultibar.stop();

Constructor

Initialize a new multiprogress container. Bars need to be added. The options/presets are used for each single bar!

constcliProgress=require('cli-progress');const<instance> = new cliProgress.MultiBar(options:object [, preset:object]);

::create()

Adds a new progress bar to the container and starts the bar. Returns regular SingleBar object which can be individually controlled.

Additional barOptions can be passed directly to the generic-bar to override the global options for a single bar instance. This can be useful to change the appearance of a single bar object. But be patient: this should only be used to override formats - DON'T try to set other global options like the terminal, synchronous flags, etc..

const<barInstance> = <instance>.create(totalValue:int, startValue:int [, payload:object = {} [, barOptions:object = {}]]);

::remove()

Removes an existing bar from the multi progress container.

<instance>.remove(<barInstance>:object);

::stop()

Stops the all progress bars

<instance>.stop();

::log()

Outputs (buffered) content on top of the multibars during operation.

Notice: newline at the end is required

Example: example-logging.js

<instance>.log("Hello World\n");

Options

The following options can be changed

  • format (type:string|function) - progress bar output format @see format section
  • fps (type:float) - the maximum update rate (default: 10)
  • stream (type:stream) - output stream to use (default: process.stderr)
  • stopOnComplete (type:boolean) - automatically call stop() when the value reaches the total (default: false)
  • clearOnComplete (type:boolean) - clear the progress bar on complete / stop() call (default: false)
  • barsize (type:int) - the length of the progress bar in chars (default: 40)
  • align (type:char) - position of the progress bar - 'left' (default), 'right' or 'center'
  • barCompleteChar (type:char) - character to use as "complete" indicator in the bar (default: "=")
  • barIncompleteChar (type:char) - character to use as "incomplete" indicator in the bar (default: "-")
  • hideCursor (type:boolean) - hide the cursor during progress operation; restored on complete (default: false) - pass null to keep terminal settings
  • linewrap (type:boolean) - disable line wrapping (default: false) - pass null to keep terminal settings; pass true to add linebreaks automatically (not recommended)
  • gracefulExit (type:boolean) - stop the bars in case of SIGINT or SIGTERM - this restores most cursor settings before exiting (default: false - subjected to change)
  • etaBuffer (type:int) - number of updates with which to calculate the eta; higher numbers give a more stable eta (default: 10)
  • etaAsynchronousUpdate (type:boolean) - trigger an eta calculation update during asynchronous rendering trigger using the current value - should only be used for long running processes in conjunction with lof fps values and large etaBuffer (default: false)
  • progressCalculationRelative (type:boolean) - progress calculation uses startValue as zero-offset (default: false)
  • synchronousUpdate (type:boolean) - trigger redraw during update() in case threshold time x2 is exceeded (default: true) - limited to single bar usage
  • noTTYOutput (type:boolean) - enable scheduled output to notty streams - e.g. redirect to files (default: false)
  • notTTYSchedule (type:int) - set the output schedule/interval for notty output in ms (default: 2000ms)
  • emptyOnZero (type:boolean) - display progress bars with 'total' of zero(0) as empty, not full (default: false)
  • forceRedraw (type:boolean) - trigger redraw on every frame even if progress remains the same; can be useful if progress bar gets overwritten by other concurrent writes to the terminal (default: false)
  • barGlue (type:string) - a "glue" string between the complete and incomplete bar elements used to insert ascii control sequences for colorization (default: empty) - Note: in case you add visible "glue" characters the barsize will be increased by the length of the glue!
  • autopadding (type: boolean) - add padding chars to formatted time and percentage to force fixed width (default: false) - Note: handled standard format functions!
  • autopaddingChar (type: string) - the character sequence used for autopadding (default: " ") - Note: due to performance optimizations this value requires a length of 3 identical chars
  • formatBar (type: function) - a custom bar formatter function which renders the bar-element (default: format-bar.js)
  • formatTime (type: function) - a custom timer formatter function which renders the formatted time elements like eta_formatted and duration-formatted (default: format-time.js)
  • formatValue (type: function) - a custom value formatter function which renders all other values (default: format-value.js)

Events

The classes extends EventEmitter which allows you to hook into different events.

See event docs for detailed information + examples.

Bar Formatting

The progressbar can be customized by using the following build-in placeholders. They can be combined in any order.

  • {bar} - the progress bar, customizable by the options barsize, barCompleteString and barIncompleteString
  • {percentage} - the current progress in percent (0-100)
  • {total} - the end value
  • {value} - the current value set by last update() call
  • {eta} - expected time of accomplishment in seconds (limmited to 115days, otherwise INF is displayed)
  • {duration} - elapsed time in seconds
  • {eta_formatted} - expected time of accomplishment formatted into appropriate units
  • {duration_formatted} - elapsed time formatted into appropriate units
  • {<payloadKeyName>} - the payload value identified by its key

Example

constopt={format: 'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}'}

is rendered as

progress [========================================] 100% | ETA: 0s | 200/200

Custom formatters

Instead of a "static" format string it is also possible to pass a custom callback function as formatter. For a full example (including params) take a look on lib/formatter.js

Example 1

functionformatter(options,params,payload){// bar grows dynamically by current progress - no whitespaces are addedconstbar=options.barCompleteString.substr(0,Math.round(params.progress*options.barsize));// end value reached ?// change color to green when finishedif(params.value>=params.total){return'# '+colors.grey(payload.task)+' '+colors.green(params.value+'/'+params.total)+' --['+bar+']-- ';}else{return'# '+payload.task+' '+colors.yellow(params.value+'/'+params.total)+' --['+bar+']-- ';}}constopt={format: formatter}

is rendered as

# Task 1 0/200 --[]--
# Task 1 98/200 --[████████████████████]--
# Task 1 200/200 --[████████████████████████████████████████]--

Example 2

You can also access the default format functions to use them within your formatter:

const{TimeFormat, ValueFormat, BarFormat, Formatter}=require('cli-progess').Format;
...

Examples

Example 1 - Set Options

// change the progress characters// set fps limit to 5// change the output stream and barsizeconstbar=new_progress.Bar({barCompleteChar: '#',barIncompleteChar: '.',fps: 5,stream: process.stdout,barsize: 65,position: 'center'});

Example 2 - Change Styles defined by Preset

// uee shades preset// change the barsizeconstbar=new_progress.Bar({barsize: 65,position: 'right'},_progress.Presets.shades_grey);

Example 3 - Custom Payload

The payload object keys should only contain keys matching standard \w+ regex!

// create new progress bar with custom token "speed"constbar=new_progress.Bar({format: 'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit'});// initialize the bar - set payload token "speed" with the default value "N/A"bar.start(200,0,{speed: "N/A"});// some code/update loop// ...// update bar value. set custom token "speed" to 125bar.update(5,{speed: '125'});// process finishedbar.stop();

Example 4 - Custom Presets

FilemyPreset.js

constcolors=require('ansi-colors');module.exports={format: colors.red(' {bar}')+' {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit',barCompleteChar: '\u2588',barIncompleteChar: '\u2591'};

Application

constmyPreset=require('./myPreset.js');constbar=new_progress.Bar({barsize: 65},myPreset);

Presets/Themes

Need a more modern appearance ? cli-progress supports predefined themes via presets. You are welcome to add your custom one :)

But keep in mind that a lot of the "special-chars" rely on Unicode - it might not work as expected on legacy systems.

Default Presets

The following presets are included by default

  • legacy - Styles as of cli-progress v1.3.0
  • shades-classic - Unicode background shades are used for the bar
  • shades-grey - Unicode background shades with grey bar
  • rect - Unicode Rectangles

Compatibility

cli-progress is designed for linux/macOS/container applications which mostly providing standard compliant tty terminals/shells. In non-tty mode it is suitable to be used with logging daemons (cyclic output).

It also works with PowerShell on Windows 10 - the legacy command prompt on outdated Windows versions won't work as expected and is not supported!

Any Questions ? Report a Bug ? Enhancements ?

Please open a new issue on GitHub

License

CLI-Progress is OpenSource and licensed under the Terms of The MIT License (X11). You're welcome to contribute!

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

Build Status

Single Bar | Multi Bar | Options | Examples | Presets | Events

CLI-Progress

easy to use progress-bar for command-line/terminal applications

Demo

Demo

Install

$ yarn add cli-progress
$ npm install cli-progress --save

Features

  • Simple, Robust and Easy to use
  • Full customizable output format (various placeholders are available)
  • Single progressbar mode
  • Multi progessbar mode
  • Custom Bar Characters
  • FPS limiter
  • ETA calculation based on elapsed time
  • Custom Tokens to display additional data (payload) within the bar
  • TTY and NOTTY mode
  • No callbacks required - designed as pure, external controlled UI widget
  • Works in Asynchronous and Synchronous tasks
  • Preset/Theme support
  • Custom bar formatters (via callback)
  • Logging during multibar operation

Usage

Multiple examples are available e.g. example.js - just try it $ node example.js

constcliProgress=require('cli-progress');// create a new progress bar instance and use shades_classic themeconstbar1=newcliProgress.SingleBar({},cliProgress.Presets.shades_classic);// start the progress bar with a total value of 200 and start value of 0bar1.start(200,0);// update the current value in your application..bar1.update(100);// stop the progress barbar1.stop();

Single Bar Mode

Demo

Example

constcliProgress=require('cli-progress');// note: you have to install this dependency manually since it's not required by cli-progressconstcolors=require('ansi-colors');// create new progress barconstb1=newcliProgress.SingleBar({format: 'CLI Progress |'+colors.cyan('{bar}')+'| {percentage}% || {value}/{total} Chunks || Speed: {speed}',barCompleteChar: '\u2588',barIncompleteChar: '\u2591',hideCursor: true});// initialize the bar - defining payload token "speed" with the default value "N/A"b1.start(200,0,{speed: "N/A"});// update valuesb1.increment();b1.update(20);// stop the barb1.stop();

Constructor

Initialize a new Progress bar. An instance can be used multiple times! it's not required to re-create it!

constcliProgress=require('cli-progress');const<instance> = new cliProgress.SingleBar(options:object [, preset:object]);

Options

::start()

Starts the progress bar and set the total and initial value

<instance>.start(totalValue:int, startValue:int [, payload:object = {}]);

::update()

Sets the current progress value and optionally the payload with values of custom tokens as a second parameter. To update payload only, set currentValue to null.

<instance>.update([currentValue:int [, payload:object = {}]]);
// update progress without altering value
<instance>.update([payload:object = {}]);

::increment()

Increases the current progress value by a specified amount (default +1). Update payload optionally

<instance>.increment([delta:int [, payload:object = {}]]);
// delta=1 assumed
<instance>.increment(payload:object = {}]);

::setTotal()

Sets the total progress value while progressbar is active. Especially useful handling dynamic tasks.

<instance>.setTotal(totalValue:int);

::stop()

Stops the progress bar and go to next line

<instance>.stop();

::updateETA()

Force eta calculation update (long running processes) without altering the progress values.

Note: you may want to increase etaBuffer size - otherwise it can cause INF eta values in case the value didn't changed within the time series.

<instance>.updateETA();

Multi Bar Mode

Demo

Example

constcliProgress=require('cli-progress');// create new containerconstmultibar=newcliProgress.MultiBar({clearOnComplete: false,hideCursor: true,format: ' {bar} | {filename} | {value}/{total}',},cliProgress.Presets.shades_grey);// add barsconstb1=multibar.create(200,0);constb2=multibar.create(1000,0);// control barsb1.increment();b2.update(20,{filename: "test1.txt"});b1.update(20,{filename: "helloworld.txt"});// stop all barsmultibar.stop();

Constructor

Initialize a new multiprogress container. Bars need to be added. The options/presets are used for each single bar!

constcliProgress=require('cli-progress');const<instance> = new cliProgress.MultiBar(options:object [, preset:object]);

::create()

Adds a new progress bar to the container and starts the bar. Returns regular SingleBar object which can be individually controlled.

Additional barOptions can be passed directly to the generic-bar to override the global options for a single bar instance. This can be useful to change the appearance of a single bar object. But be patient: this should only be used to override formats - DON'T try to set other global options like the terminal, synchronous flags, etc..

const<barInstance> = <instance>.create(totalValue:int, startValue:int [, payload:object = {} [, barOptions:object = {}]]);

::remove()

Removes an existing bar from the multi progress container.

<instance>.remove(<barInstance>:object);

::stop()

Stops the all progress bars

<instance>.stop();

::log()

Outputs (buffered) content on top of the multibars during operation.

Notice: newline at the end is required

Example: example-logging.js

<instance>.log("Hello World\n");

Options

The following options can be changed

  • format (type:string|function) - progress bar output format @see format section
  • fps (type:float) - the maximum update rate (default: 10)
  • stream (type:stream) - output stream to use (default: process.stderr)
  • stopOnComplete (type:boolean) - automatically call stop() when the value reaches the total (default: false)
  • clearOnComplete (type:boolean) - clear the progress bar on complete / stop() call (default: false)
  • barsize (type:int) - the length of the progress bar in chars (default: 40)
  • align (type:char) - position of the progress bar - 'left' (default), 'right' or 'center'
  • barCompleteChar (type:char) - character to use as "complete" indicator in the bar (default: "=")
  • barIncompleteChar (type:char) - character to use as "incomplete" indicator in the bar (default: "-")
  • hideCursor (type:boolean) - hide the cursor during progress operation; restored on complete (default: false) - pass null to keep terminal settings
  • linewrap (type:boolean) - disable line wrapping (default: false) - pass null to keep terminal settings; pass true to add linebreaks automatically (not recommended)
  • gracefulExit (type:boolean) - stop the bars in case of SIGINT or SIGTERM - this restores most cursor settings before exiting (default: false - subjected to change)
  • etaBuffer (type:int) - number of updates with which to calculate the eta; higher numbers give a more stable eta (default: 10)
  • etaAsynchronousUpdate (type:boolean) - trigger an eta calculation update during asynchronous rendering trigger using the current value - should only be used for long running processes in conjunction with lof fps values and large etaBuffer (default: false)
  • progressCalculationRelative (type:boolean) - progress calculation uses startValue as zero-offset (default: false)
  • synchronousUpdate (type:boolean) - trigger redraw during update() in case threshold time x2 is exceeded (default: true) - limited to single bar usage
  • noTTYOutput (type:boolean) - enable scheduled output to notty streams - e.g. redirect to files (default: false)
  • notTTYSchedule (type:int) - set the output schedule/interval for notty output in ms (default: 2000ms)
  • emptyOnZero (type:boolean) - display progress bars with 'total' of zero(0) as empty, not full (default: false)
  • forceRedraw (type:boolean) - trigger redraw on every frame even if progress remains the same; can be useful if progress bar gets overwritten by other concurrent writes to the terminal (default: false)
  • barGlue (type:string) - a "glue" string between the complete and incomplete bar elements used to insert ascii control sequences for colorization (default: empty) - Note: in case you add visible "glue" characters the barsize will be increased by the length of the glue!
  • autopadding (type: boolean) - add padding chars to formatted time and percentage to force fixed width (default: false) - Note: handled standard format functions!
  • autopaddingChar (type: string) - the character sequence used for autopadding (default: " ") - Note: due to performance optimizations this value requires a length of 3 identical chars
  • formatBar (type: function) - a custom bar formatter function which renders the bar-element (default: format-bar.js)
  • formatTime (type: function) - a custom timer formatter function which renders the formatted time elements like eta_formatted and duration-formatted (default: format-time.js)
  • formatValue (type: function) - a custom value formatter function which renders all other values (default: format-value.js)

Events

The classes extends EventEmitter which allows you to hook into different events.

See event docs for detailed information + examples.

Bar Formatting

The progressbar can be customized by using the following build-in placeholders. They can be combined in any order.

  • {bar} - the progress bar, customizable by the options barsize, barCompleteString and barIncompleteString
  • {percentage} - the current progress in percent (0-100)
  • {total} - the end value
  • {value} - the current value set by last update() call
  • {eta} - expected time of accomplishment in seconds (limmited to 115days, otherwise INF is displayed)
  • {duration} - elapsed time in seconds
  • {eta_formatted} - expected time of accomplishment formatted into appropriate units
  • {duration_formatted} - elapsed time formatted into appropriate units
  • {<payloadKeyName>} - the payload value identified by its key

Example

constopt={format: 'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}'}

is rendered as

progress [========================================] 100% | ETA: 0s | 200/200

Custom formatters

Instead of a "static" format string it is also possible to pass a custom callback function as formatter. For a full example (including params) take a look on lib/formatter.js

Example 1

functionformatter(options,params,payload){// bar grows dynamically by current progress - no whitespaces are addedconstbar=options.barCompleteString.substr(0,Math.round(params.progress*options.barsize));// end value reached ?// change color to green when finishedif(params.value>=params.total){return'# '+colors.grey(payload.task)+' '+colors.green(params.value+'/'+params.total)+' --['+bar+']-- ';}else{return'# '+payload.task+' '+colors.yellow(params.value+'/'+params.total)+' --['+bar+']-- ';}}constopt={format: formatter}

is rendered as

# Task 1 0/200 --[]--
# Task 1 98/200 --[████████████████████]--
# Task 1 200/200 --[████████████████████████████████████████]--

Example 2

You can also access the default format functions to use them within your formatter:

const{TimeFormat, ValueFormat, BarFormat, Formatter}=require('cli-progess').Format;
...

Examples

Example 1 - Set Options

// change the progress characters// set fps limit to 5// change the output stream and barsizeconstbar=new_progress.Bar({barCompleteChar: '#',barIncompleteChar: '.',fps: 5,stream: process.stdout,barsize: 65,position: 'center'});

Example 2 - Change Styles defined by Preset

// uee shades preset// change the barsizeconstbar=new_progress.Bar({barsize: 65,position: 'right'},_progress.Presets.shades_grey);

Example 3 - Custom Payload

The payload object keys should only contain keys matching standard \w+ regex!

// create new progress bar with custom token "speed"constbar=new_progress.Bar({format: 'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit'});// initialize the bar - set payload token "speed" with the default value "N/A"bar.start(200,0,{speed: "N/A"});// some code/update loop// ...// update bar value. set custom token "speed" to 125bar.update(5,{speed: '125'});// process finishedbar.stop();

Example 4 - Custom Presets

FilemyPreset.js

constcolors=require('ansi-colors');module.exports={format: colors.red(' {bar}')+' {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit',barCompleteChar: '\u2588',barIncompleteChar: '\u2591'};

Application

constmyPreset=require('./myPreset.js');constbar=new_progress.Bar({barsize: 65},myPreset);

Presets/Themes

Need a more modern appearance ? cli-progress supports predefined themes via presets. You are welcome to add your custom one :)

But keep in mind that a lot of the "special-chars" rely on Unicode - it might not work as expected on legacy systems.

Default Presets

The following presets are included by default

  • legacy - Styles as of cli-progress v1.3.0
  • shades-classic - Unicode background shades are used for the bar
  • shades-grey - Unicode background shades with grey bar
  • rect - Unicode Rectangles

Compatibility

cli-progress is designed for linux/macOS/container applications which mostly providing standard compliant tty terminals/shells. In non-tty mode it is suitable to be used with logging daemons (cyclic output).

It also works with PowerShell on Windows 10 - the legacy command prompt on outdated Windows versions won't work as expected and is not supported!

Any Questions ? Report a Bug ? Enhancements ?

Please open a new issue on GitHub

License

CLI-Progress is OpenSource and licensed under the Terms of The MIT License (X11). You're welcome to contribute!

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Build Status

Single Bar | Multi Bar | Options | Examples | Presets | Events

CLI-Progress

easy to use progress-bar for command-line/terminal applications

Demo

Demo

Install

$ yarn add cli-progress
$ npm install cli-progress --save

Features

  • Simple, Robust and Easy to use
  • Full customizable output format (various placeholders are available)
  • Single progressbar mode
  • Multi progessbar mode
  • Custom Bar Characters
  • FPS limiter
  • ETA calculation based on elapsed time
  • Custom Tokens to display additional data (payload) within the bar
  • TTY and NOTTY mode
  • No callbacks required - designed as pure, external controlled UI widget
  • Works in Asynchronous and Synchronous tasks
  • Preset/Theme support
  • Custom bar formatters (via callback)
  • Logging during multibar operation

Usage

Multiple examples are available e.g. example.js - just try it $ node example.js

constcliProgress=require('cli-progress');// create a new progress bar instance and use shades_classic themeconstbar1=newcliProgress.SingleBar({},cliProgress.Presets.shades_classic);// start the progress bar with a total value of 200 and start value of 0bar1.start(200,0);// update the current value in your application..bar1.update(100);// stop the progress barbar1.stop();

Single Bar Mode

Demo

Example

constcliProgress=require('cli-progress');// note: you have to install this dependency manually since it's not required by cli-progressconstcolors=require('ansi-colors');// create new progress barconstb1=newcliProgress.SingleBar({format: 'CLI Progress |'+colors.cyan('{bar}')+'| {percentage}% || {value}/{total} Chunks || Speed: {speed}',barCompleteChar: '\u2588',barIncompleteChar: '\u2591',hideCursor: true});// initialize the bar - defining payload token "speed" with the default value "N/A"b1.start(200,0,{speed: "N/A"});// update valuesb1.increment();b1.update(20);// stop the barb1.stop();

Constructor

Initialize a new Progress bar. An instance can be used multiple times! it's not required to re-create it!

constcliProgress=require('cli-progress');const<instance> = new cliProgress.SingleBar(options:object [, preset:object]);

Options

::start()

Starts the progress bar and set the total and initial value

<instance>.start(totalValue:int, startValue:int [, payload:object = {}]);

::update()

Sets the current progress value and optionally the payload with values of custom tokens as a second parameter. To update payload only, set currentValue to null.

<instance>.update([currentValue:int [, payload:object = {}]]);
// update progress without altering value
<instance>.update([payload:object = {}]);

::increment()

Increases the current progress value by a specified amount (default +1). Update payload optionally

<instance>.increment([delta:int [, payload:object = {}]]);
// delta=1 assumed
<instance>.increment(payload:object = {}]);

::setTotal()

Sets the total progress value while progressbar is active. Especially useful handling dynamic tasks.

<instance>.setTotal(totalValue:int);

::stop()

Stops the progress bar and go to next line

<instance>.stop();

::updateETA()

Force eta calculation update (long running processes) without altering the progress values.

Note: you may want to increase etaBuffer size - otherwise it can cause INF eta values in case the value didn't changed within the time series.

<instance>.updateETA();

Multi Bar Mode

Demo

Example

constcliProgress=require('cli-progress');// create new containerconstmultibar=newcliProgress.MultiBar({clearOnComplete: false,hideCursor: true,format: ' {bar} | {filename} | {value}/{total}',},cliProgress.Presets.shades_grey);// add barsconstb1=multibar.create(200,0);constb2=multibar.create(1000,0);// control barsb1.increment();b2.update(20,{filename: "test1.txt"});b1.update(20,{filename: "helloworld.txt"});// stop all barsmultibar.stop();

Constructor

Initialize a new multiprogress container. Bars need to be added. The options/presets are used for each single bar!

constcliProgress=require('cli-progress');const<instance> = new cliProgress.MultiBar(options:object [, preset:object]);

::create()

Adds a new progress bar to the container and starts the bar. Returns regular SingleBar object which can be individually controlled.

Additional barOptions can be passed directly to the generic-bar to override the global options for a single bar instance. This can be useful to change the appearance of a single bar object. But be patient: this should only be used to override formats - DON'T try to set other global options like the terminal, synchronous flags, etc..

const<barInstance> = <instance>.create(totalValue:int, startValue:int [, payload:object = {} [, barOptions:object = {}]]);

::remove()

Removes an existing bar from the multi progress container.

<instance>.remove(<barInstance>:object);

::stop()

Stops the all progress bars

<instance>.stop();

::log()

Outputs (buffered) content on top of the multibars during operation.

Notice: newline at the end is required

Example: example-logging.js

<instance>.log("Hello World\n");

Options

The following options can be changed

  • format (type:string|function) - progress bar output format @see format section
  • fps (type:float) - the maximum update rate (default: 10)
  • stream (type:stream) - output stream to use (default: process.stderr)
  • stopOnComplete (type:boolean) - automatically call stop() when the value reaches the total (default: false)
  • clearOnComplete (type:boolean) - clear the progress bar on complete / stop() call (default: false)
  • barsize (type:int) - the length of the progress bar in chars (default: 40)
  • align (type:char) - position of the progress bar - 'left' (default), 'right' or 'center'
  • barCompleteChar (type:char) - character to use as "complete" indicator in the bar (default: "=")
  • barIncompleteChar (type:char) - character to use as "incomplete" indicator in the bar (default: "-")
  • hideCursor (type:boolean) - hide the cursor during progress operation; restored on complete (default: false) - pass null to keep terminal settings
  • linewrap (type:boolean) - disable line wrapping (default: false) - pass null to keep terminal settings; pass true to add linebreaks automatically (not recommended)
  • gracefulExit (type:boolean) - stop the bars in case of SIGINT or SIGTERM - this restores most cursor settings before exiting (default: false - subjected to change)
  • etaBuffer (type:int) - number of updates with which to calculate the eta; higher numbers give a more stable eta (default: 10)
  • etaAsynchronousUpdate (type:boolean) - trigger an eta calculation update during asynchronous rendering trigger using the current value - should only be used for long running processes in conjunction with lof fps values and large etaBuffer (default: false)
  • progressCalculationRelative (type:boolean) - progress calculation uses startValue as zero-offset (default: false)
  • synchronousUpdate (type:boolean) - trigger redraw during update() in case threshold time x2 is exceeded (default: true) - limited to single bar usage
  • noTTYOutput (type:boolean) - enable scheduled output to notty streams - e.g. redirect to files (default: false)
  • notTTYSchedule (type:int) - set the output schedule/interval for notty output in ms (default: 2000ms)
  • emptyOnZero (type:boolean) - display progress bars with 'total' of zero(0) as empty, not full (default: false)
  • forceRedraw (type:boolean) - trigger redraw on every frame even if progress remains the same; can be useful if progress bar gets overwritten by other concurrent writes to the terminal (default: false)
  • barGlue (type:string) - a "glue" string between the complete and incomplete bar elements used to insert ascii control sequences for colorization (default: empty) - Note: in case you add visible "glue" characters the barsize will be increased by the length of the glue!
  • autopadding (type: boolean) - add padding chars to formatted time and percentage to force fixed width (default: false) - Note: handled standard format functions!
  • autopaddingChar (type: string) - the character sequence used for autopadding (default: " ") - Note: due to performance optimizations this value requires a length of 3 identical chars
  • formatBar (type: function) - a custom bar formatter function which renders the bar-element (default: format-bar.js)
  • formatTime (type: function) - a custom timer formatter function which renders the formatted time elements like eta_formatted and duration-formatted (default: format-time.js)
  • formatValue (type: function) - a custom value formatter function which renders all other values (default: format-value.js)

Events

The classes extends EventEmitter which allows you to hook into different events.

See event docs for detailed information + examples.

Bar Formatting

The progressbar can be customized by using the following build-in placeholders. They can be combined in any order.

  • {bar} - the progress bar, customizable by the options barsize, barCompleteString and barIncompleteString
  • {percentage} - the current progress in percent (0-100)
  • {total} - the end value
  • {value} - the current value set by last update() call
  • {eta} - expected time of accomplishment in seconds (limmited to 115days, otherwise INF is displayed)
  • {duration} - elapsed time in seconds
  • {eta_formatted} - expected time of accomplishment formatted into appropriate units
  • {duration_formatted} - elapsed time formatted into appropriate units
  • {<payloadKeyName>} - the payload value identified by its key

Example

constopt={format: 'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}'}

is rendered as

progress [========================================] 100% | ETA: 0s | 200/200

Custom formatters

Instead of a "static" format string it is also possible to pass a custom callback function as formatter. For a full example (including params) take a look on lib/formatter.js

Example 1

functionformatter(options,params,payload){// bar grows dynamically by current progress - no whitespaces are addedconstbar=options.barCompleteString.substr(0,Math.round(params.progress*options.barsize));// end value reached ?// change color to green when finishedif(params.value>=params.total){return'# '+colors.grey(payload.task)+' '+colors.green(params.value+'/'+params.total)+' --['+bar+']-- ';}else{return'# '+payload.task+' '+colors.yellow(params.value+'/'+params.total)+' --['+bar+']-- ';}}constopt={format: formatter}

is rendered as

# Task 1 0/200 --[]--
# Task 1 98/200 --[████████████████████]--
# Task 1 200/200 --[████████████████████████████████████████]--

Example 2

You can also access the default format functions to use them within your formatter:

const{TimeFormat, ValueFormat, BarFormat, Formatter}=require('cli-progess').Format;
...

Examples

Example 1 - Set Options

// change the progress characters// set fps limit to 5// change the output stream and barsizeconstbar=new_progress.Bar({barCompleteChar: '#',barIncompleteChar: '.',fps: 5,stream: process.stdout,barsize: 65,position: 'center'});

Example 2 - Change Styles defined by Preset

// uee shades preset// change the barsizeconstbar=new_progress.Bar({barsize: 65,position: 'right'},_progress.Presets.shades_grey);

Example 3 - Custom Payload

The payload object keys should only contain keys matching standard \w+ regex!

// create new progress bar with custom token "speed"constbar=new_progress.Bar({format: 'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit'});// initialize the bar - set payload token "speed" with the default value "N/A"bar.start(200,0,{speed: "N/A"});// some code/update loop// ...// update bar value. set custom token "speed" to 125bar.update(5,{speed: '125'});// process finishedbar.stop();

Example 4 - Custom Presets

FilemyPreset.js

constcolors=require('ansi-colors');module.exports={format: colors.red(' {bar}')+' {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit',barCompleteChar: '\u2588',barIncompleteChar: '\u2591'};

Application

constmyPreset=require('./myPreset.js');constbar=new_progress.Bar({barsize: 65},myPreset);

Presets/Themes

Need a more modern appearance ? cli-progress supports predefined themes via presets. You are welcome to add your custom one :)

But keep in mind that a lot of the "special-chars" rely on Unicode - it might not work as expected on legacy systems.

Default Presets

The following presets are included by default

  • legacy - Styles as of cli-progress v1.3.0
  • shades-classic - Unicode background shades are used for the bar
  • shades-grey - Unicode background shades with grey bar
  • rect - Unicode Rectangles

Compatibility

cli-progress is designed for linux/macOS/container applications which mostly providing standard compliant tty terminals/shells. In non-tty mode it is suitable to be used with logging daemons (cyclic output).

It also works with PowerShell on Windows 10 - the legacy command prompt on outdated Windows versions won't work as expected and is not supported!

Any Questions ? Report a Bug ? Enhancements ?

Please open a new issue on GitHub

License

CLI-Progress is OpenSource and licensed under the Terms of The MIT License (X11). You're welcome to contribute!

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Build Status

Single Bar | Multi Bar | Options | Examples | Presets | Events

CLI-Progress

easy to use progress-bar for command-line/terminal applications

Demo

Demo

Install

$ yarn add cli-progress
$ npm install cli-progress --save

Features

  • Simple, Robust and Easy to use
  • Full customizable output format (various placeholders are available)
  • Single progressbar mode
  • Multi progessbar mode
  • Custom Bar Characters
  • FPS limiter
  • ETA calculation based on elapsed time
  • Custom Tokens to display additional data (payload) within the bar
  • TTY and NOTTY mode
  • No callbacks required - designed as pure, external controlled UI widget
  • Works in Asynchronous and Synchronous tasks
  • Preset/Theme support
  • Custom bar formatters (via callback)
  • Logging during multibar operation

Usage

Multiple examples are available e.g. example.js - just try it $ node example.js

constcliProgress=require('cli-progress');// create a new progress bar instance and use shades_classic themeconstbar1=newcliProgress.SingleBar({},cliProgress.Presets.shades_classic);// start the progress bar with a total value of 200 and start value of 0bar1.start(200,0);// update the current value in your application..bar1.update(100);// stop the progress barbar1.stop();

Single Bar Mode

Demo

Example

constcliProgress=require('cli-progress');// note: you have to install this dependency manually since it's not required by cli-progressconstcolors=require('ansi-colors');// create new progress barconstb1=newcliProgress.SingleBar({format: 'CLI Progress |'+colors.cyan('{bar}')+'| {percentage}% || {value}/{total} Chunks || Speed: {speed}',barCompleteChar: '\u2588',barIncompleteChar: '\u2591',hideCursor: true});// initialize the bar - defining payload token "speed" with the default value "N/A"b1.start(200,0,{speed: "N/A"});// update valuesb1.increment();b1.update(20);// stop the barb1.stop();

Constructor

Initialize a new Progress bar. An instance can be used multiple times! it's not required to re-create it!

constcliProgress=require('cli-progress');const<instance> = new cliProgress.SingleBar(options:object [, preset:object]);

Options

::start()

Starts the progress bar and set the total and initial value

<instance>.start(totalValue:int, startValue:int [, payload:object = {}]);

::update()

Sets the current progress value and optionally the payload with values of custom tokens as a second parameter. To update payload only, set currentValue to null.

<instance>.update([currentValue:int [, payload:object = {}]]);
// update progress without altering value
<instance>.update([payload:object = {}]);

::increment()

Increases the current progress value by a specified amount (default +1). Update payload optionally

<instance>.increment([delta:int [, payload:object = {}]]);
// delta=1 assumed
<instance>.increment(payload:object = {}]);

::setTotal()

Sets the total progress value while progressbar is active. Especially useful handling dynamic tasks.

<instance>.setTotal(totalValue:int);

::stop()

Stops the progress bar and go to next line

<instance>.stop();

::updateETA()

Force eta calculation update (long running processes) without altering the progress values.

Note: you may want to increase etaBuffer size - otherwise it can cause INF eta values in case the value didn't changed within the time series.

<instance>.updateETA();

Multi Bar Mode

Demo

Example

constcliProgress=require('cli-progress');// create new containerconstmultibar=newcliProgress.MultiBar({clearOnComplete: false,hideCursor: true,format: ' {bar} | {filename} | {value}/{total}',},cliProgress.Presets.shades_grey);// add barsconstb1=multibar.create(200,0);constb2=multibar.create(1000,0);// control barsb1.increment();b2.update(20,{filename: "test1.txt"});b1.update(20,{filename: "helloworld.txt"});// stop all barsmultibar.stop();

Constructor

Initialize a new multiprogress container. Bars need to be added. The options/presets are used for each single bar!

constcliProgress=require('cli-progress');const<instance> = new cliProgress.MultiBar(options:object [, preset:object]);

::create()

Adds a new progress bar to the container and starts the bar. Returns regular SingleBar object which can be individually controlled.

Additional barOptions can be passed directly to the generic-bar to override the global options for a single bar instance. This can be useful to change the appearance of a single bar object. But be patient: this should only be used to override formats - DON'T try to set other global options like the terminal, synchronous flags, etc..

const<barInstance> = <instance>.create(totalValue:int, startValue:int [, payload:object = {} [, barOptions:object = {}]]);

::remove()

Removes an existing bar from the multi progress container.

<instance>.remove(<barInstance>:object);

::stop()

Stops the all progress bars

<instance>.stop();

::log()

Outputs (buffered) content on top of the multibars during operation.

Notice: newline at the end is required

Example: example-logging.js

<instance>.log("Hello World\n");

Options

The following options can be changed

  • format (type:string|function) - progress bar output format @see format section
  • fps (type:float) - the maximum update rate (default: 10)
  • stream (type:stream) - output stream to use (default: process.stderr)
  • stopOnComplete (type:boolean) - automatically call stop() when the value reaches the total (default: false)
  • clearOnComplete (type:boolean) - clear the progress bar on complete / stop() call (default: false)
  • barsize (type:int) - the length of the progress bar in chars (default: 40)
  • align (type:char) - position of the progress bar - 'left' (default), 'right' or 'center'
  • barCompleteChar (type:char) - character to use as "complete" indicator in the bar (default: "=")
  • barIncompleteChar (type:char) - character to use as "incomplete" indicator in the bar (default: "-")
  • hideCursor (type:boolean) - hide the cursor during progress operation; restored on complete (default: false) - pass null to keep terminal settings
  • linewrap (type:boolean) - disable line wrapping (default: false) - pass null to keep terminal settings; pass true to add linebreaks automatically (not recommended)
  • gracefulExit (type:boolean) - stop the bars in case of SIGINT or SIGTERM - this restores most cursor settings before exiting (default: false - subjected to change)
  • etaBuffer (type:int) - number of updates with which to calculate the eta; higher numbers give a more stable eta (default: 10)
  • etaAsynchronousUpdate (type:boolean) - trigger an eta calculation update during asynchronous rendering trigger using the current value - should only be used for long running processes in conjunction with lof fps values and large etaBuffer (default: false)
  • progressCalculationRelative (type:boolean) - progress calculation uses startValue as zero-offset (default: false)
  • synchronousUpdate (type:boolean) - trigger redraw during update() in case threshold time x2 is exceeded (default: true) - limited to single bar usage
  • noTTYOutput (type:boolean) - enable scheduled output to notty streams - e.g. redirect to files (default: false)
  • notTTYSchedule (type:int) - set the output schedule/interval for notty output in ms (default: 2000ms)
  • emptyOnZero (type:boolean) - display progress bars with 'total' of zero(0) as empty, not full (default: false)
  • forceRedraw (type:boolean) - trigger redraw on every frame even if progress remains the same; can be useful if progress bar gets overwritten by other concurrent writes to the terminal (default: false)
  • barGlue (type:string) - a "glue" string between the complete and incomplete bar elements used to insert ascii control sequences for colorization (default: empty) - Note: in case you add visible "glue" characters the barsize will be increased by the length of the glue!
  • autopadding (type: boolean) - add padding chars to formatted time and percentage to force fixed width (default: false) - Note: handled standard format functions!
  • autopaddingChar (type: string) - the character sequence used for autopadding (default: " ") - Note: due to performance optimizations this value requires a length of 3 identical chars
  • formatBar (type: function) - a custom bar formatter function which renders the bar-element (default: format-bar.js)
  • formatTime (type: function) - a custom timer formatter function which renders the formatted time elements like eta_formatted and duration-formatted (default: format-time.js)
  • formatValue (type: function) - a custom value formatter function which renders all other values (default: format-value.js)

Events

The classes extends EventEmitter which allows you to hook into different events.

See event docs for detailed information + examples.

Bar Formatting

The progressbar can be customized by using the following build-in placeholders. They can be combined in any order.

  • {bar} - the progress bar, customizable by the options barsize, barCompleteString and barIncompleteString
  • {percentage} - the current progress in percent (0-100)
  • {total} - the end value
  • {value} - the current value set by last update() call
  • {eta} - expected time of accomplishment in seconds (limmited to 115days, otherwise INF is displayed)
  • {duration} - elapsed time in seconds
  • {eta_formatted} - expected time of accomplishment formatted into appropriate units
  • {duration_formatted} - elapsed time formatted into appropriate units
  • {<payloadKeyName>} - the payload value identified by its key

Example

constopt={format: 'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}'}

is rendered as

progress [========================================] 100% | ETA: 0s | 200/200

Custom formatters

Instead of a "static" format string it is also possible to pass a custom callback function as formatter. For a full example (including params) take a look on lib/formatter.js

Example 1

functionformatter(options,params,payload){// bar grows dynamically by current progress - no whitespaces are addedconstbar=options.barCompleteString.substr(0,Math.round(params.progress*options.barsize));// end value reached ?// change color to green when finishedif(params.value>=params.total){return'# '+colors.grey(payload.task)+' '+colors.green(params.value+'/'+params.total)+' --['+bar+']-- ';}else{return'# '+payload.task+' '+colors.yellow(params.value+'/'+params.total)+' --['+bar+']-- ';}}constopt={format: formatter}

is rendered as

# Task 1 0/200 --[]--
# Task 1 98/200 --[████████████████████]--
# Task 1 200/200 --[████████████████████████████████████████]--

Example 2

You can also access the default format functions to use them within your formatter:

const{TimeFormat, ValueFormat, BarFormat, Formatter}=require('cli-progess').Format;
...

Examples

Example 1 - Set Options

// change the progress characters// set fps limit to 5// change the output stream and barsizeconstbar=new_progress.Bar({barCompleteChar: '#',barIncompleteChar: '.',fps: 5,stream: process.stdout,barsize: 65,position: 'center'});

Example 2 - Change Styles defined by Preset

// uee shades preset// change the barsizeconstbar=new_progress.Bar({barsize: 65,position: 'right'},_progress.Presets.shades_grey);

Example 3 - Custom Payload

The payload object keys should only contain keys matching standard \w+ regex!

// create new progress bar with custom token "speed"constbar=new_progress.Bar({format: 'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit'});// initialize the bar - set payload token "speed" with the default value "N/A"bar.start(200,0,{speed: "N/A"});// some code/update loop// ...// update bar value. set custom token "speed" to 125bar.update(5,{speed: '125'});// process finishedbar.stop();

Example 4 - Custom Presets

FilemyPreset.js

constcolors=require('ansi-colors');module.exports={format: colors.red(' {bar}')+' {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit',barCompleteChar: '\u2588',barIncompleteChar: '\u2591'};

Application

constmyPreset=require('./myPreset.js');constbar=new_progress.Bar({barsize: 65},myPreset);

Presets/Themes

Need a more modern appearance ? cli-progress supports predefined themes via presets. You are welcome to add your custom one :)

But keep in mind that a lot of the "special-chars" rely on Unicode - it might not work as expected on legacy systems.

Default Presets

The following presets are included by default

  • legacy - Styles as of cli-progress v1.3.0
  • shades-classic - Unicode background shades are used for the bar
  • shades-grey - Unicode background shades with grey bar
  • rect - Unicode Rectangles

Compatibility

cli-progress is designed for linux/macOS/container applications which mostly providing standard compliant tty terminals/shells. In non-tty mode it is suitable to be used with logging daemons (cyclic output).

It also works with PowerShell on Windows 10 - the legacy command prompt on outdated Windows versions won't work as expected and is not supported!

Any Questions ? Report a Bug ? Enhancements ?

Please open a new issue on GitHub

License

CLI-Progress is OpenSource and licensed under the Terms of The MIT License (X11). You're welcome to contribute!

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

Build Status

Single Bar | Multi Bar | Options | Examples | Presets | Events

CLI-Progress

easy to use progress-bar for command-line/terminal applications

Demo

Demo

Install

$ yarn add cli-progress
$ npm install cli-progress --save

Features

  • Simple, Robust and Easy to use
  • Full customizable output format (various placeholders are available)
  • Single progressbar mode
  • Multi progessbar mode
  • Custom Bar Characters
  • FPS limiter
  • ETA calculation based on elapsed time
  • Custom Tokens to display additional data (payload) within the bar
  • TTY and NOTTY mode
  • No callbacks required - designed as pure, external controlled UI widget
  • Works in Asynchronous and Synchronous tasks
  • Preset/Theme support
  • Custom bar formatters (via callback)
  • Logging during multibar operation

Usage

Multiple examples are available e.g. example.js - just try it $ node example.js

constcliProgress=require('cli-progress');// create a new progress bar instance and use shades_classic themeconstbar1=newcliProgress.SingleBar({},cliProgress.Presets.shades_classic);// start the progress bar with a total value of 200 and start value of 0bar1.start(200,0);// update the current value in your application..bar1.update(100);// stop the progress barbar1.stop();

Single Bar Mode

Demo

Example

constcliProgress=require('cli-progress');// note: you have to install this dependency manually since it's not required by cli-progressconstcolors=require('ansi-colors');// create new progress barconstb1=newcliProgress.SingleBar({format: 'CLI Progress |'+colors.cyan('{bar}')+'| {percentage}% || {value}/{total} Chunks || Speed: {speed}',barCompleteChar: '\u2588',barIncompleteChar: '\u2591',hideCursor: true});// initialize the bar - defining payload token "speed" with the default value "N/A"b1.start(200,0,{speed: "N/A"});// update valuesb1.increment();b1.update(20);// stop the barb1.stop();

Constructor

Initialize a new Progress bar. An instance can be used multiple times! it's not required to re-create it!

constcliProgress=require('cli-progress');const<instance> = new cliProgress.SingleBar(options:object [, preset:object]);

Options

::start()

Starts the progress bar and set the total and initial value

<instance>.start(totalValue:int, startValue:int [, payload:object = {}]);

::update()

Sets the current progress value and optionally the payload with values of custom tokens as a second parameter. To update payload only, set currentValue to null.

<instance>.update([currentValue:int [, payload:object = {}]]);
// update progress without altering value
<instance>.update([payload:object = {}]);

::increment()

Increases the current progress value by a specified amount (default +1). Update payload optionally

<instance>.increment([delta:int [, payload:object = {}]]);
// delta=1 assumed
<instance>.increment(payload:object = {}]);

::setTotal()

Sets the total progress value while progressbar is active. Especially useful handling dynamic tasks.

<instance>.setTotal(totalValue:int);

::stop()

Stops the progress bar and go to next line

<instance>.stop();

::updateETA()

Force eta calculation update (long running processes) without altering the progress values.

Note: you may want to increase etaBuffer size - otherwise it can cause INF eta values in case the value didn't changed within the time series.

<instance>.updateETA();

Multi Bar Mode

Demo

Example

constcliProgress=require('cli-progress');// create new containerconstmultibar=newcliProgress.MultiBar({clearOnComplete: false,hideCursor: true,format: ' {bar} | {filename} | {value}/{total}',},cliProgress.Presets.shades_grey);// add barsconstb1=multibar.create(200,0);constb2=multibar.create(1000,0);// control barsb1.increment();b2.update(20,{filename: "test1.txt"});b1.update(20,{filename: "helloworld.txt"});// stop all barsmultibar.stop();

Constructor

Initialize a new multiprogress container. Bars need to be added. The options/presets are used for each single bar!

constcliProgress=require('cli-progress');const<instance> = new cliProgress.MultiBar(options:object [, preset:object]);

::create()

Adds a new progress bar to the container and starts the bar. Returns regular SingleBar object which can be individually controlled.

Additional barOptions can be passed directly to the generic-bar to override the global options for a single bar instance. This can be useful to change the appearance of a single bar object. But be patient: this should only be used to override formats - DON'T try to set other global options like the terminal, synchronous flags, etc..

const<barInstance> = <instance>.create(totalValue:int, startValue:int [, payload:object = {} [, barOptions:object = {}]]);

::remove()

Removes an existing bar from the multi progress container.

<instance>.remove(<barInstance>:object);

::stop()

Stops the all progress bars

<instance>.stop();

::log()

Outputs (buffered) content on top of the multibars during operation.

Notice: newline at the end is required

Example: example-logging.js

<instance>.log("Hello World\n");

Options

The following options can be changed

  • format (type:string|function) - progress bar output format @see format section
  • fps (type:float) - the maximum update rate (default: 10)
  • stream (type:stream) - output stream to use (default: process.stderr)
  • stopOnComplete (type:boolean) - automatically call stop() when the value reaches the total (default: false)
  • clearOnComplete (type:boolean) - clear the progress bar on complete / stop() call (default: false)
  • barsize (type:int) - the length of the progress bar in chars (default: 40)
  • align (type:char) - position of the progress bar - 'left' (default), 'right' or 'center'
  • barCompleteChar (type:char) - character to use as "complete" indicator in the bar (default: "=")
  • barIncompleteChar (type:char) - character to use as "incomplete" indicator in the bar (default: "-")
  • hideCursor (type:boolean) - hide the cursor during progress operation; restored on complete (default: false) - pass null to keep terminal settings
  • linewrap (type:boolean) - disable line wrapping (default: false) - pass null to keep terminal settings; pass true to add linebreaks automatically (not recommended)
  • gracefulExit (type:boolean) - stop the bars in case of SIGINT or SIGTERM - this restores most cursor settings before exiting (default: false - subjected to change)
  • etaBuffer (type:int) - number of updates with which to calculate the eta; higher numbers give a more stable eta (default: 10)
  • etaAsynchronousUpdate (type:boolean) - trigger an eta calculation update during asynchronous rendering trigger using the current value - should only be used for long running processes in conjunction with lof fps values and large etaBuffer (default: false)
  • progressCalculationRelative (type:boolean) - progress calculation uses startValue as zero-offset (default: false)
  • synchronousUpdate (type:boolean) - trigger redraw during update() in case threshold time x2 is exceeded (default: true) - limited to single bar usage
  • noTTYOutput (type:boolean) - enable scheduled output to notty streams - e.g. redirect to files (default: false)
  • notTTYSchedule (type:int) - set the output schedule/interval for notty output in ms (default: 2000ms)
  • emptyOnZero (type:boolean) - display progress bars with 'total' of zero(0) as empty, not full (default: false)
  • forceRedraw (type:boolean) - trigger redraw on every frame even if progress remains the same; can be useful if progress bar gets overwritten by other concurrent writes to the terminal (default: false)
  • barGlue (type:string) - a "glue" string between the complete and incomplete bar elements used to insert ascii control sequences for colorization (default: empty) - Note: in case you add visible "glue" characters the barsize will be increased by the length of the glue!
  • autopadding (type: boolean) - add padding chars to formatted time and percentage to force fixed width (default: false) - Note: handled standard format functions!
  • autopaddingChar (type: string) - the character sequence used for autopadding (default: " ") - Note: due to performance optimizations this value requires a length of 3 identical chars
  • formatBar (type: function) - a custom bar formatter function which renders the bar-element (default: format-bar.js)
  • formatTime (type: function) - a custom timer formatter function which renders the formatted time elements like eta_formatted and duration-formatted (default: format-time.js)
  • formatValue (type: function) - a custom value formatter function which renders all other values (default: format-value.js)

Events

The classes extends EventEmitter which allows you to hook into different events.

See event docs for detailed information + examples.

Bar Formatting

The progressbar can be customized by using the following build-in placeholders. They can be combined in any order.

  • {bar} - the progress bar, customizable by the options barsize, barCompleteString and barIncompleteString
  • {percentage} - the current progress in percent (0-100)
  • {total} - the end value
  • {value} - the current value set by last update() call
  • {eta} - expected time of accomplishment in seconds (limmited to 115days, otherwise INF is displayed)
  • {duration} - elapsed time in seconds
  • {eta_formatted} - expected time of accomplishment formatted into appropriate units
  • {duration_formatted} - elapsed time formatted into appropriate units
  • {<payloadKeyName>} - the payload value identified by its key

Example

constopt={format: 'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}'}

is rendered as

progress [========================================] 100% | ETA: 0s | 200/200

Custom formatters

Instead of a "static" format string it is also possible to pass a custom callback function as formatter. For a full example (including params) take a look on lib/formatter.js

Example 1

functionformatter(options,params,payload){// bar grows dynamically by current progress - no whitespaces are addedconstbar=options.barCompleteString.substr(0,Math.round(params.progress*options.barsize));// end value reached ?// change color to green when finishedif(params.value>=params.total){return'# '+colors.grey(payload.task)+' '+colors.green(params.value+'/'+params.total)+' --['+bar+']-- ';}else{return'# '+payload.task+' '+colors.yellow(params.value+'/'+params.total)+' --['+bar+']-- ';}}constopt={format: formatter}

is rendered as

# Task 1 0/200 --[]--
# Task 1 98/200 --[████████████████████]--
# Task 1 200/200 --[████████████████████████████████████████]--

Example 2

You can also access the default format functions to use them within your formatter:

const{TimeFormat, ValueFormat, BarFormat, Formatter}=require('cli-progess').Format;
...

Examples

Example 1 - Set Options

// change the progress characters// set fps limit to 5// change the output stream and barsizeconstbar=new_progress.Bar({barCompleteChar: '#',barIncompleteChar: '.',fps: 5,stream: process.stdout,barsize: 65,position: 'center'});

Example 2 - Change Styles defined by Preset

// uee shades preset// change the barsizeconstbar=new_progress.Bar({barsize: 65,position: 'right'},_progress.Presets.shades_grey);

Example 3 - Custom Payload

The payload object keys should only contain keys matching standard \w+ regex!

// create new progress bar with custom token "speed"constbar=new_progress.Bar({format: 'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit'});// initialize the bar - set payload token "speed" with the default value "N/A"bar.start(200,0,{speed: "N/A"});// some code/update loop// ...// update bar value. set custom token "speed" to 125bar.update(5,{speed: '125'});// process finishedbar.stop();

Example 4 - Custom Presets

FilemyPreset.js

constcolors=require('ansi-colors');module.exports={format: colors.red(' {bar}')+' {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit',barCompleteChar: '\u2588',barIncompleteChar: '\u2591'};

Application

constmyPreset=require('./myPreset.js');constbar=new_progress.Bar({barsize: 65},myPreset);

Presets/Themes

Need a more modern appearance ? cli-progress supports predefined themes via presets. You are welcome to add your custom one :)

But keep in mind that a lot of the "special-chars" rely on Unicode - it might not work as expected on legacy systems.

Default Presets

The following presets are included by default

  • legacy - Styles as of cli-progress v1.3.0
  • shades-classic - Unicode background shades are used for the bar
  • shades-grey - Unicode background shades with grey bar
  • rect - Unicode Rectangles

Compatibility

cli-progress is designed for linux/macOS/container applications which mostly providing standard compliant tty terminals/shells. In non-tty mode it is suitable to be used with logging daemons (cyclic output).

It also works with PowerShell on Windows 10 - the legacy command prompt on outdated Windows versions won't work as expected and is not supported!

Any Questions ? Report a Bug ? Enhancements ?

Please open a new issue on GitHub

License

CLI-Progress is OpenSource and licensed under the Terms of The MIT License (X11). You're welcome to contribute!

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Build Status

Single Bar | Multi Bar | Options | Examples | Presets | Events

CLI-Progress

easy to use progress-bar for command-line/terminal applications

Demo

Demo

Install

$ yarn add cli-progress
$ npm install cli-progress --save

Features

  • Simple, Robust and Easy to use
  • Full customizable output format (various placeholders are available)
  • Single progressbar mode
  • Multi progessbar mode
  • Custom Bar Characters
  • FPS limiter
  • ETA calculation based on elapsed time
  • Custom Tokens to display additional data (payload) within the bar
  • TTY and NOTTY mode
  • No callbacks required - designed as pure, external controlled UI widget
  • Works in Asynchronous and Synchronous tasks
  • Preset/Theme support
  • Custom bar formatters (via callback)
  • Logging during multibar operation

Usage

Multiple examples are available e.g. example.js - just try it $ node example.js

constcliProgress=require('cli-progress');// create a new progress bar instance and use shades_classic themeconstbar1=newcliProgress.SingleBar({},cliProgress.Presets.shades_classic);// start the progress bar with a total value of 200 and start value of 0bar1.start(200,0);// update the current value in your application..bar1.update(100);// stop the progress barbar1.stop();

Single Bar Mode

Demo

Example

constcliProgress=require('cli-progress');// note: you have to install this dependency manually since it's not required by cli-progressconstcolors=require('ansi-colors');// create new progress barconstb1=newcliProgress.SingleBar({format: 'CLI Progress |'+colors.cyan('{bar}')+'| {percentage}% || {value}/{total} Chunks || Speed: {speed}',barCompleteChar: '\u2588',barIncompleteChar: '\u2591',hideCursor: true});// initialize the bar - defining payload token "speed" with the default value "N/A"b1.start(200,0,{speed: "N/A"});// update valuesb1.increment();b1.update(20);// stop the barb1.stop();

Constructor

Initialize a new Progress bar. An instance can be used multiple times! it's not required to re-create it!

constcliProgress=require('cli-progress');const<instance> = new cliProgress.SingleBar(options:object [, preset:object]);

Options

::start()

Starts the progress bar and set the total and initial value

<instance>.start(totalValue:int, startValue:int [, payload:object = {}]);

::update()

Sets the current progress value and optionally the payload with values of custom tokens as a second parameter. To update payload only, set currentValue to null.

<instance>.update([currentValue:int [, payload:object = {}]]);
// update progress without altering value
<instance>.update([payload:object = {}]);

::increment()

Increases the current progress value by a specified amount (default +1). Update payload optionally

<instance>.increment([delta:int [, payload:object = {}]]);
// delta=1 assumed
<instance>.increment(payload:object = {}]);

::setTotal()

Sets the total progress value while progressbar is active. Especially useful handling dynamic tasks.

<instance>.setTotal(totalValue:int);

::stop()

Stops the progress bar and go to next line

<instance>.stop();

::updateETA()

Force eta calculation update (long running processes) without altering the progress values.

Note: you may want to increase etaBuffer size - otherwise it can cause INF eta values in case the value didn't changed within the time series.

<instance>.updateETA();

Multi Bar Mode

Demo

Example

constcliProgress=require('cli-progress');// create new containerconstmultibar=newcliProgress.MultiBar({clearOnComplete: false,hideCursor: true,format: ' {bar} | {filename} | {value}/{total}',},cliProgress.Presets.shades_grey);// add barsconstb1=multibar.create(200,0);constb2=multibar.create(1000,0);// control barsb1.increment();b2.update(20,{filename: "test1.txt"});b1.update(20,{filename: "helloworld.txt"});// stop all barsmultibar.stop();

Constructor

Initialize a new multiprogress container. Bars need to be added. The options/presets are used for each single bar!

constcliProgress=require('cli-progress');const<instance> = new cliProgress.MultiBar(options:object [, preset:object]);

::create()

Adds a new progress bar to the container and starts the bar. Returns regular SingleBar object which can be individually controlled.

Additional barOptions can be passed directly to the generic-bar to override the global options for a single bar instance. This can be useful to change the appearance of a single bar object. But be patient: this should only be used to override formats - DON'T try to set other global options like the terminal, synchronous flags, etc..

const<barInstance> = <instance>.create(totalValue:int, startValue:int [, payload:object = {} [, barOptions:object = {}]]);

::remove()

Removes an existing bar from the multi progress container.

<instance>.remove(<barInstance>:object);

::stop()

Stops the all progress bars

<instance>.stop();

::log()

Outputs (buffered) content on top of the multibars during operation.

Notice: newline at the end is required

Example: example-logging.js

<instance>.log("Hello World\n");

Options

The following options can be changed

  • format (type:string|function) - progress bar output format @see format section
  • fps (type:float) - the maximum update rate (default: 10)
  • stream (type:stream) - output stream to use (default: process.stderr)
  • stopOnComplete (type:boolean) - automatically call stop() when the value reaches the total (default: false)
  • clearOnComplete (type:boolean) - clear the progress bar on complete / stop() call (default: false)
  • barsize (type:int) - the length of the progress bar in chars (default: 40)
  • align (type:char) - position of the progress bar - 'left' (default), 'right' or 'center'
  • barCompleteChar (type:char) - character to use as "complete" indicator in the bar (default: "=")
  • barIncompleteChar (type:char) - character to use as "incomplete" indicator in the bar (default: "-")
  • hideCursor (type:boolean) - hide the cursor during progress operation; restored on complete (default: false) - pass null to keep terminal settings
  • linewrap (type:boolean) - disable line wrapping (default: false) - pass null to keep terminal settings; pass true to add linebreaks automatically (not recommended)
  • gracefulExit (type:boolean) - stop the bars in case of SIGINT or SIGTERM - this restores most cursor settings before exiting (default: false - subjected to change)
  • etaBuffer (type:int) - number of updates with which to calculate the eta; higher numbers give a more stable eta (default: 10)
  • etaAsynchronousUpdate (type:boolean) - trigger an eta calculation update during asynchronous rendering trigger using the current value - should only be used for long running processes in conjunction with lof fps values and large etaBuffer (default: false)
  • progressCalculationRelative (type:boolean) - progress calculation uses startValue as zero-offset (default: false)
  • synchronousUpdate (type:boolean) - trigger redraw during update() in case threshold time x2 is exceeded (default: true) - limited to single bar usage
  • noTTYOutput (type:boolean) - enable scheduled output to notty streams - e.g. redirect to files (default: false)
  • notTTYSchedule (type:int) - set the output schedule/interval for notty output in ms (default: 2000ms)
  • emptyOnZero (type:boolean) - display progress bars with 'total' of zero(0) as empty, not full (default: false)
  • forceRedraw (type:boolean) - trigger redraw on every frame even if progress remains the same; can be useful if progress bar gets overwritten by other concurrent writes to the terminal (default: false)
  • barGlue (type:string) - a "glue" string between the complete and incomplete bar elements used to insert ascii control sequences for colorization (default: empty) - Note: in case you add visible "glue" characters the barsize will be increased by the length of the glue!
  • autopadding (type: boolean) - add padding chars to formatted time and percentage to force fixed width (default: false) - Note: handled standard format functions!
  • autopaddingChar (type: string) - the character sequence used for autopadding (default: " ") - Note: due to performance optimizations this value requires a length of 3 identical chars
  • formatBar (type: function) - a custom bar formatter function which renders the bar-element (default: format-bar.js)
  • formatTime (type: function) - a custom timer formatter function which renders the formatted time elements like eta_formatted and duration-formatted (default: format-time.js)
  • formatValue (type: function) - a custom value formatter function which renders all other values (default: format-value.js)

Events

The classes extends EventEmitter which allows you to hook into different events.

See event docs for detailed information + examples.

Bar Formatting

The progressbar can be customized by using the following build-in placeholders. They can be combined in any order.

  • {bar} - the progress bar, customizable by the options barsize, barCompleteString and barIncompleteString
  • {percentage} - the current progress in percent (0-100)
  • {total} - the end value
  • {value} - the current value set by last update() call
  • {eta} - expected time of accomplishment in seconds (limmited to 115days, otherwise INF is displayed)
  • {duration} - elapsed time in seconds
  • {eta_formatted} - expected time of accomplishment formatted into appropriate units
  • {duration_formatted} - elapsed time formatted into appropriate units
  • {<payloadKeyName>} - the payload value identified by its key

Example

constopt={format: 'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}'}

is rendered as

progress [========================================] 100% | ETA: 0s | 200/200

Custom formatters

Instead of a "static" format string it is also possible to pass a custom callback function as formatter. For a full example (including params) take a look on lib/formatter.js

Example 1

functionformatter(options,params,payload){// bar grows dynamically by current progress - no whitespaces are addedconstbar=options.barCompleteString.substr(0,Math.round(params.progress*options.barsize));// end value reached ?// change color to green when finishedif(params.value>=params.total){return'# '+colors.grey(payload.task)+' '+colors.green(params.value+'/'+params.total)+' --['+bar+']-- ';}else{return'# '+payload.task+' '+colors.yellow(params.value+'/'+params.total)+' --['+bar+']-- ';}}constopt={format: formatter}

is rendered as

# Task 1 0/200 --[]--
# Task 1 98/200 --[████████████████████]--
# Task 1 200/200 --[████████████████████████████████████████]--

Example 2

You can also access the default format functions to use them within your formatter:

const{TimeFormat, ValueFormat, BarFormat, Formatter}=require('cli-progess').Format;
...

Examples

Example 1 - Set Options

// change the progress characters// set fps limit to 5// change the output stream and barsizeconstbar=new_progress.Bar({barCompleteChar: '#',barIncompleteChar: '.',fps: 5,stream: process.stdout,barsize: 65,position: 'center'});

Example 2 - Change Styles defined by Preset

// uee shades preset// change the barsizeconstbar=new_progress.Bar({barsize: 65,position: 'right'},_progress.Presets.shades_grey);

Example 3 - Custom Payload

The payload object keys should only contain keys matching standard \w+ regex!

// create new progress bar with custom token "speed"constbar=new_progress.Bar({format: 'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit'});// initialize the bar - set payload token "speed" with the default value "N/A"bar.start(200,0,{speed: "N/A"});// some code/update loop// ...// update bar value. set custom token "speed" to 125bar.update(5,{speed: '125'});// process finishedbar.stop();

Example 4 - Custom Presets

FilemyPreset.js

constcolors=require('ansi-colors');module.exports={format: colors.red(' {bar}')+' {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit',barCompleteChar: '\u2588',barIncompleteChar: '\u2591'};

Application

constmyPreset=require('./myPreset.js');constbar=new_progress.Bar({barsize: 65},myPreset);

Presets/Themes

Need a more modern appearance ? cli-progress supports predefined themes via presets. You are welcome to add your custom one :)

But keep in mind that a lot of the "special-chars" rely on Unicode - it might not work as expected on legacy systems.

Default Presets

The following presets are included by default

  • legacy - Styles as of cli-progress v1.3.0
  • shades-classic - Unicode background shades are used for the bar
  • shades-grey - Unicode background shades with grey bar
  • rect - Unicode Rectangles

Compatibility

cli-progress is designed for linux/macOS/container applications which mostly providing standard compliant tty terminals/shells. In non-tty mode it is suitable to be used with logging daemons (cyclic output).

It also works with PowerShell on Windows 10 - the legacy command prompt on outdated Windows versions won't work as expected and is not supported!

Any Questions ? Report a Bug ? Enhancements ?

Please open a new issue on GitHub

License

CLI-Progress is OpenSource and licensed under the Terms of The MIT License (X11). You're welcome to contribute!

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Build Status

Single Bar | Multi Bar | Options | Examples | Presets | Events

CLI-Progress

easy to use progress-bar for command-line/terminal applications

Demo

Demo

Install

$ yarn add cli-progress
$ npm install cli-progress --save

Features

  • Simple, Robust and Easy to use
  • Full customizable output format (various placeholders are available)
  • Single progressbar mode
  • Multi progessbar mode
  • Custom Bar Characters
  • FPS limiter
  • ETA calculation based on elapsed time
  • Custom Tokens to display additional data (payload) within the bar
  • TTY and NOTTY mode
  • No callbacks required - designed as pure, external controlled UI widget
  • Works in Asynchronous and Synchronous tasks
  • Preset/Theme support
  • Custom bar formatters (via callback)
  • Logging during multibar operation

Usage

Multiple examples are available e.g. example.js - just try it $ node example.js

constcliProgress=require('cli-progress');// create a new progress bar instance and use shades_classic themeconstbar1=newcliProgress.SingleBar({},cliProgress.Presets.shades_classic);// start the progress bar with a total value of 200 and start value of 0bar1.start(200,0);// update the current value in your application..bar1.update(100);// stop the progress barbar1.stop();

Single Bar Mode

Demo

Example

constcliProgress=require('cli-progress');// note: you have to install this dependency manually since it's not required by cli-progressconstcolors=require('ansi-colors');// create new progress barconstb1=newcliProgress.SingleBar({format: 'CLI Progress |'+colors.cyan('{bar}')+'| {percentage}% || {value}/{total} Chunks || Speed: {speed}',barCompleteChar: '\u2588',barIncompleteChar: '\u2591',hideCursor: true});// initialize the bar - defining payload token "speed" with the default value "N/A"b1.start(200,0,{speed: "N/A"});// update valuesb1.increment();b1.update(20);// stop the barb1.stop();

Constructor

Initialize a new Progress bar. An instance can be used multiple times! it's not required to re-create it!

constcliProgress=require('cli-progress');const<instance> = new cliProgress.SingleBar(options:object [, preset:object]);

Options

::start()

Starts the progress bar and set the total and initial value

<instance>.start(totalValue:int, startValue:int [, payload:object = {}]);

::update()

Sets the current progress value and optionally the payload with values of custom tokens as a second parameter. To update payload only, set currentValue to null.

<instance>.update([currentValue:int [, payload:object = {}]]);
// update progress without altering value
<instance>.update([payload:object = {}]);

::increment()

Increases the current progress value by a specified amount (default +1). Update payload optionally

<instance>.increment([delta:int [, payload:object = {}]]);
// delta=1 assumed
<instance>.increment(payload:object = {}]);

::setTotal()

Sets the total progress value while progressbar is active. Especially useful handling dynamic tasks.

<instance>.setTotal(totalValue:int);

::stop()

Stops the progress bar and go to next line

<instance>.stop();

::updateETA()

Force eta calculation update (long running processes) without altering the progress values.

Note: you may want to increase etaBuffer size - otherwise it can cause INF eta values in case the value didn't changed within the time series.

<instance>.updateETA();

Multi Bar Mode

Demo

Example

constcliProgress=require('cli-progress');// create new containerconstmultibar=newcliProgress.MultiBar({clearOnComplete: false,hideCursor: true,format: ' {bar} | {filename} | {value}/{total}',},cliProgress.Presets.shades_grey);// add barsconstb1=multibar.create(200,0);constb2=multibar.create(1000,0);// control barsb1.increment();b2.update(20,{filename: "test1.txt"});b1.update(20,{filename: "helloworld.txt"});// stop all barsmultibar.stop();

Constructor

Initialize a new multiprogress container. Bars need to be added. The options/presets are used for each single bar!

constcliProgress=require('cli-progress');const<instance> = new cliProgress.MultiBar(options:object [, preset:object]);

::create()

Adds a new progress bar to the container and starts the bar. Returns regular SingleBar object which can be individually controlled.

Additional barOptions can be passed directly to the generic-bar to override the global options for a single bar instance. This can be useful to change the appearance of a single bar object. But be patient: this should only be used to override formats - DON'T try to set other global options like the terminal, synchronous flags, etc..

const<barInstance> = <instance>.create(totalValue:int, startValue:int [, payload:object = {} [, barOptions:object = {}]]);

::remove()

Removes an existing bar from the multi progress container.

<instance>.remove(<barInstance>:object);

::stop()

Stops the all progress bars

<instance>.stop();

::log()

Outputs (buffered) content on top of the multibars during operation.

Notice: newline at the end is required

Example: example-logging.js

<instance>.log("Hello World\n");

Options

The following options can be changed

  • format (type:string|function) - progress bar output format @see format section
  • fps (type:float) - the maximum update rate (default: 10)
  • stream (type:stream) - output stream to use (default: process.stderr)
  • stopOnComplete (type:boolean) - automatically call stop() when the value reaches the total (default: false)
  • clearOnComplete (type:boolean) - clear the progress bar on complete / stop() call (default: false)
  • barsize (type:int) - the length of the progress bar in chars (default: 40)
  • align (type:char) - position of the progress bar - 'left' (default), 'right' or 'center'
  • barCompleteChar (type:char) - character to use as "complete" indicator in the bar (default: "=")
  • barIncompleteChar (type:char) - character to use as "incomplete" indicator in the bar (default: "-")
  • hideCursor (type:boolean) - hide the cursor during progress operation; restored on complete (default: false) - pass null to keep terminal settings
  • linewrap (type:boolean) - disable line wrapping (default: false) - pass null to keep terminal settings; pass true to add linebreaks automatically (not recommended)
  • gracefulExit (type:boolean) - stop the bars in case of SIGINT or SIGTERM - this restores most cursor settings before exiting (default: false - subjected to change)
  • etaBuffer (type:int) - number of updates with which to calculate the eta; higher numbers give a more stable eta (default: 10)
  • etaAsynchronousUpdate (type:boolean) - trigger an eta calculation update during asynchronous rendering trigger using the current value - should only be used for long running processes in conjunction with lof fps values and large etaBuffer (default: false)
  • progressCalculationRelative (type:boolean) - progress calculation uses startValue as zero-offset (default: false)
  • synchronousUpdate (type:boolean) - trigger redraw during update() in case threshold time x2 is exceeded (default: true) - limited to single bar usage
  • noTTYOutput (type:boolean) - enable scheduled output to notty streams - e.g. redirect to files (default: false)
  • notTTYSchedule (type:int) - set the output schedule/interval for notty output in ms (default: 2000ms)
  • emptyOnZero (type:boolean) - display progress bars with 'total' of zero(0) as empty, not full (default: false)
  • forceRedraw (type:boolean) - trigger redraw on every frame even if progress remains the same; can be useful if progress bar gets overwritten by other concurrent writes to the terminal (default: false)
  • barGlue (type:string) - a "glue" string between the complete and incomplete bar elements used to insert ascii control sequences for colorization (default: empty) - Note: in case you add visible "glue" characters the barsize will be increased by the length of the glue!
  • autopadding (type: boolean) - add padding chars to formatted time and percentage to force fixed width (default: false) - Note: handled standard format functions!
  • autopaddingChar (type: string) - the character sequence used for autopadding (default: " ") - Note: due to performance optimizations this value requires a length of 3 identical chars
  • formatBar (type: function) - a custom bar formatter function which renders the bar-element (default: format-bar.js)
  • formatTime (type: function) - a custom timer formatter function which renders the formatted time elements like eta_formatted and duration-formatted (default: format-time.js)
  • formatValue (type: function) - a custom value formatter function which renders all other values (default: format-value.js)

Events

The classes extends EventEmitter which allows you to hook into different events.

See event docs for detailed information + examples.

Bar Formatting

The progressbar can be customized by using the following build-in placeholders. They can be combined in any order.

  • {bar} - the progress bar, customizable by the options barsize, barCompleteString and barIncompleteString
  • {percentage} - the current progress in percent (0-100)
  • {total} - the end value
  • {value} - the current value set by last update() call
  • {eta} - expected time of accomplishment in seconds (limmited to 115days, otherwise INF is displayed)
  • {duration} - elapsed time in seconds
  • {eta_formatted} - expected time of accomplishment formatted into appropriate units
  • {duration_formatted} - elapsed time formatted into appropriate units
  • {<payloadKeyName>} - the payload value identified by its key

Example

constopt={format: 'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}'}

is rendered as

progress [========================================] 100% | ETA: 0s | 200/200

Custom formatters

Instead of a "static" format string it is also possible to pass a custom callback function as formatter. For a full example (including params) take a look on lib/formatter.js

Example 1

functionformatter(options,params,payload){// bar grows dynamically by current progress - no whitespaces are addedconstbar=options.barCompleteString.substr(0,Math.round(params.progress*options.barsize));// end value reached ?// change color to green when finishedif(params.value>=params.total){return'# '+colors.grey(payload.task)+' '+colors.green(params.value+'/'+params.total)+' --['+bar+']-- ';}else{return'# '+payload.task+' '+colors.yellow(params.value+'/'+params.total)+' --['+bar+']-- ';}}constopt={format: formatter}

is rendered as

# Task 1 0/200 --[]--
# Task 1 98/200 --[████████████████████]--
# Task 1 200/200 --[████████████████████████████████████████]--

Example 2

You can also access the default format functions to use them within your formatter:

const{TimeFormat, ValueFormat, BarFormat, Formatter}=require('cli-progess').Format;
...

Examples

Example 1 - Set Options

// change the progress characters// set fps limit to 5// change the output stream and barsizeconstbar=new_progress.Bar({barCompleteChar: '#',barIncompleteChar: '.',fps: 5,stream: process.stdout,barsize: 65,position: 'center'});

Example 2 - Change Styles defined by Preset

// uee shades preset// change the barsizeconstbar=new_progress.Bar({barsize: 65,position: 'right'},_progress.Presets.shades_grey);

Example 3 - Custom Payload

The payload object keys should only contain keys matching standard \w+ regex!

// create new progress bar with custom token "speed"constbar=new_progress.Bar({format: 'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit'});// initialize the bar - set payload token "speed" with the default value "N/A"bar.start(200,0,{speed: "N/A"});// some code/update loop// ...// update bar value. set custom token "speed" to 125bar.update(5,{speed: '125'});// process finishedbar.stop();

Example 4 - Custom Presets

FilemyPreset.js

constcolors=require('ansi-colors');module.exports={format: colors.red(' {bar}')+' {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit',barCompleteChar: '\u2588',barIncompleteChar: '\u2591'};

Application

constmyPreset=require('./myPreset.js');constbar=new_progress.Bar({barsize: 65},myPreset);

Presets/Themes

Need a more modern appearance ? cli-progress supports predefined themes via presets. You are welcome to add your custom one :)

But keep in mind that a lot of the "special-chars" rely on Unicode - it might not work as expected on legacy systems.

Default Presets

The following presets are included by default

  • legacy - Styles as of cli-progress v1.3.0
  • shades-classic - Unicode background shades are used for the bar
  • shades-grey - Unicode background shades with grey bar
  • rect - Unicode Rectangles

Compatibility

cli-progress is designed for linux/macOS/container applications which mostly providing standard compliant tty terminals/shells. In non-tty mode it is suitable to be used with logging daemons (cyclic output).

It also works with PowerShell on Windows 10 - the legacy command prompt on outdated Windows versions won't work as expected and is not supported!

Any Questions ? Report a Bug ? Enhancements ?

Please open a new issue on GitHub

License

CLI-Progress is OpenSource and licensed under the Terms of The MIT License (X11). You're welcome to contribute!

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

Build Status

Single Bar | Multi Bar | Options | Examples | Presets | Events

CLI-Progress

easy to use progress-bar for command-line/terminal applications

Demo

Demo

Install

$ yarn add cli-progress
$ npm install cli-progress --save

Features

  • Simple, Robust and Easy to use
  • Full customizable output format (various placeholders are available)
  • Single progressbar mode
  • Multi progessbar mode
  • Custom Bar Characters
  • FPS limiter
  • ETA calculation based on elapsed time
  • Custom Tokens to display additional data (payload) within the bar
  • TTY and NOTTY mode
  • No callbacks required - designed as pure, external controlled UI widget
  • Works in Asynchronous and Synchronous tasks
  • Preset/Theme support
  • Custom bar formatters (via callback)
  • Logging during multibar operation

Usage

Multiple examples are available e.g. example.js - just try it $ node example.js

constcliProgress=require('cli-progress');// create a new progress bar instance and use shades_classic themeconstbar1=newcliProgress.SingleBar({},cliProgress.Presets.shades_classic);// start the progress bar with a total value of 200 and start value of 0bar1.start(200,0);// update the current value in your application..bar1.update(100);// stop the progress barbar1.stop();

Single Bar Mode

Demo

Example

constcliProgress=require('cli-progress');// note: you have to install this dependency manually since it's not required by cli-progressconstcolors=require('ansi-colors');// create new progress barconstb1=newcliProgress.SingleBar({format: 'CLI Progress |'+colors.cyan('{bar}')+'| {percentage}% || {value}/{total} Chunks || Speed: {speed}',barCompleteChar: '\u2588',barIncompleteChar: '\u2591',hideCursor: true});// initialize the bar - defining payload token "speed" with the default value "N/A"b1.start(200,0,{speed: "N/A"});// update valuesb1.increment();b1.update(20);// stop the barb1.stop();

Constructor

Initialize a new Progress bar. An instance can be used multiple times! it's not required to re-create it!

constcliProgress=require('cli-progress');const<instance> = new cliProgress.SingleBar(options:object [, preset:object]);

Options

::start()

Starts the progress bar and set the total and initial value

<instance>.start(totalValue:int, startValue:int [, payload:object = {}]);

::update()

Sets the current progress value and optionally the payload with values of custom tokens as a second parameter. To update payload only, set currentValue to null.

<instance>.update([currentValue:int [, payload:object = {}]]);
// update progress without altering value
<instance>.update([payload:object = {}]);

::increment()

Increases the current progress value by a specified amount (default +1). Update payload optionally

<instance>.increment([delta:int [, payload:object = {}]]);
// delta=1 assumed
<instance>.increment(payload:object = {}]);

::setTotal()

Sets the total progress value while progressbar is active. Especially useful handling dynamic tasks.

<instance>.setTotal(totalValue:int);

::stop()

Stops the progress bar and go to next line

<instance>.stop();

::updateETA()

Force eta calculation update (long running processes) without altering the progress values.

Note: you may want to increase etaBuffer size - otherwise it can cause INF eta values in case the value didn't changed within the time series.

<instance>.updateETA();

Multi Bar Mode

Demo

Example

constcliProgress=require('cli-progress');// create new containerconstmultibar=newcliProgress.MultiBar({clearOnComplete: false,hideCursor: true,format: ' {bar} | {filename} | {value}/{total}',},cliProgress.Presets.shades_grey);// add barsconstb1=multibar.create(200,0);constb2=multibar.create(1000,0);// control barsb1.increment();b2.update(20,{filename: "test1.txt"});b1.update(20,{filename: "helloworld.txt"});// stop all barsmultibar.stop();

Constructor

Initialize a new multiprogress container. Bars need to be added. The options/presets are used for each single bar!

constcliProgress=require('cli-progress');const<instance> = new cliProgress.MultiBar(options:object [, preset:object]);

::create()

Adds a new progress bar to the container and starts the bar. Returns regular SingleBar object which can be individually controlled.

Additional barOptions can be passed directly to the generic-bar to override the global options for a single bar instance. This can be useful to change the appearance of a single bar object. But be patient: this should only be used to override formats - DON'T try to set other global options like the terminal, synchronous flags, etc..

const<barInstance> = <instance>.create(totalValue:int, startValue:int [, payload:object = {} [, barOptions:object = {}]]);

::remove()

Removes an existing bar from the multi progress container.

<instance>.remove(<barInstance>:object);

::stop()

Stops the all progress bars

<instance>.stop();

::log()

Outputs (buffered) content on top of the multibars during operation.

Notice: newline at the end is required

Example: example-logging.js

<instance>.log("Hello World\n");

Options

The following options can be changed

  • format (type:string|function) - progress bar output format @see format section
  • fps (type:float) - the maximum update rate (default: 10)
  • stream (type:stream) - output stream to use (default: process.stderr)
  • stopOnComplete (type:boolean) - automatically call stop() when the value reaches the total (default: false)
  • clearOnComplete (type:boolean) - clear the progress bar on complete / stop() call (default: false)
  • barsize (type:int) - the length of the progress bar in chars (default: 40)
  • align (type:char) - position of the progress bar - 'left' (default), 'right' or 'center'
  • barCompleteChar (type:char) - character to use as "complete" indicator in the bar (default: "=")
  • barIncompleteChar (type:char) - character to use as "incomplete" indicator in the bar (default: "-")
  • hideCursor (type:boolean) - hide the cursor during progress operation; restored on complete (default: false) - pass null to keep terminal settings
  • linewrap (type:boolean) - disable line wrapping (default: false) - pass null to keep terminal settings; pass true to add linebreaks automatically (not recommended)
  • gracefulExit (type:boolean) - stop the bars in case of SIGINT or SIGTERM - this restores most cursor settings before exiting (default: false - subjected to change)
  • etaBuffer (type:int) - number of updates with which to calculate the eta; higher numbers give a more stable eta (default: 10)
  • etaAsynchronousUpdate (type:boolean) - trigger an eta calculation update during asynchronous rendering trigger using the current value - should only be used for long running processes in conjunction with lof fps values and large etaBuffer (default: false)
  • progressCalculationRelative (type:boolean) - progress calculation uses startValue as zero-offset (default: false)
  • synchronousUpdate (type:boolean) - trigger redraw during update() in case threshold time x2 is exceeded (default: true) - limited to single bar usage
  • noTTYOutput (type:boolean) - enable scheduled output to notty streams - e.g. redirect to files (default: false)
  • notTTYSchedule (type:int) - set the output schedule/interval for notty output in ms (default: 2000ms)
  • emptyOnZero (type:boolean) - display progress bars with 'total' of zero(0) as empty, not full (default: false)
  • forceRedraw (type:boolean) - trigger redraw on every frame even if progress remains the same; can be useful if progress bar gets overwritten by other concurrent writes to the terminal (default: false)
  • barGlue (type:string) - a "glue" string between the complete and incomplete bar elements used to insert ascii control sequences for colorization (default: empty) - Note: in case you add visible "glue" characters the barsize will be increased by the length of the glue!
  • autopadding (type: boolean) - add padding chars to formatted time and percentage to force fixed width (default: false) - Note: handled standard format functions!
  • autopaddingChar (type: string) - the character sequence used for autopadding (default: " ") - Note: due to performance optimizations this value requires a length of 3 identical chars
  • formatBar (type: function) - a custom bar formatter function which renders the bar-element (default: format-bar.js)
  • formatTime (type: function) - a custom timer formatter function which renders the formatted time elements like eta_formatted and duration-formatted (default: format-time.js)
  • formatValue (type: function) - a custom value formatter function which renders all other values (default: format-value.js)

Events

The classes extends EventEmitter which allows you to hook into different events.

See event docs for detailed information + examples.

Bar Formatting

The progressbar can be customized by using the following build-in placeholders. They can be combined in any order.

  • {bar} - the progress bar, customizable by the options barsize, barCompleteString and barIncompleteString
  • {percentage} - the current progress in percent (0-100)
  • {total} - the end value
  • {value} - the current value set by last update() call
  • {eta} - expected time of accomplishment in seconds (limmited to 115days, otherwise INF is displayed)
  • {duration} - elapsed time in seconds
  • {eta_formatted} - expected time of accomplishment formatted into appropriate units
  • {duration_formatted} - elapsed time formatted into appropriate units
  • {<payloadKeyName>} - the payload value identified by its key

Example

constopt={format: 'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total}'}

is rendered as

progress [========================================] 100% | ETA: 0s | 200/200

Custom formatters

Instead of a "static" format string it is also possible to pass a custom callback function as formatter. For a full example (including params) take a look on lib/formatter.js

Example 1

functionformatter(options,params,payload){// bar grows dynamically by current progress - no whitespaces are addedconstbar=options.barCompleteString.substr(0,Math.round(params.progress*options.barsize));// end value reached ?// change color to green when finishedif(params.value>=params.total){return'# '+colors.grey(payload.task)+' '+colors.green(params.value+'/'+params.total)+' --['+bar+']-- ';}else{return'# '+payload.task+' '+colors.yellow(params.value+'/'+params.total)+' --['+bar+']-- ';}}constopt={format: formatter}

is rendered as

# Task 1 0/200 --[]--
# Task 1 98/200 --[████████████████████]--
# Task 1 200/200 --[████████████████████████████████████████]--

Example 2

You can also access the default format functions to use them within your formatter:

const{TimeFormat, ValueFormat, BarFormat, Formatter}=require('cli-progess').Format;
...

Examples

Example 1 - Set Options

// change the progress characters// set fps limit to 5// change the output stream and barsizeconstbar=new_progress.Bar({barCompleteChar: '#',barIncompleteChar: '.',fps: 5,stream: process.stdout,barsize: 65,position: 'center'});

Example 2 - Change Styles defined by Preset

// uee shades preset// change the barsizeconstbar=new_progress.Bar({barsize: 65,position: 'right'},_progress.Presets.shades_grey);

Example 3 - Custom Payload

The payload object keys should only contain keys matching standard \w+ regex!

// create new progress bar with custom token "speed"constbar=new_progress.Bar({format: 'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit'});// initialize the bar - set payload token "speed" with the default value "N/A"bar.start(200,0,{speed: "N/A"});// some code/update loop// ...// update bar value. set custom token "speed" to 125bar.update(5,{speed: '125'});// process finishedbar.stop();

Example 4 - Custom Presets

FilemyPreset.js

constcolors=require('ansi-colors');module.exports={format: colors.red(' {bar}')+' {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit',barCompleteChar: '\u2588',barIncompleteChar: '\u2591'};

Application

constmyPreset=require('./myPreset.js');constbar=new_progress.Bar({barsize: 65},myPreset);

Presets/Themes

Need a more modern appearance ? cli-progress supports predefined themes via presets. You are welcome to add your custom one :)

But keep in mind that a lot of the "special-chars" rely on Unicode - it might not work as expected on legacy systems.

Default Presets

The following presets are included by default

  • legacy - Styles as of cli-progress v1.3.0
  • shades-classic - Unicode background shades are used for the bar
  • shades-grey - Unicode background shades with grey bar
  • rect - Unicode Rectangles

Compatibility

cli-progress is designed for linux/macOS/container applications which mostly providing standard compliant tty terminals/shells. In non-tty mode it is suitable to be used with logging daemons (cyclic output).

It also works with PowerShell on Windows 10 - the legacy command prompt on outdated Windows versions won't work as expected and is not supported!

Any Questions ? Report a Bug ? Enhancements ?

Please open a new issue on GitHub

License

CLI-Progress is OpenSource and licensed under the Terms of The MIT License (X11). You're welcome to contribute!

Releases

Packages

Used by

Contributors

Languages