Detalhes do pacote

cli-progress

npkgz17.1mMIT3.12.0

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

cli, tty, terminal, progress

readme (leia-me)

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

const cliProgress = require('cli-progress');

// create a new progress bar instance and use shades_classic theme
const bar1 = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);

// start the progress bar with a total value of 200 and start value of 0
bar1.start(200, 0);

// update the current value in your application..
bar1.update(100);

// stop the progress bar
bar1.stop();

Single Bar Mode

Demo

Example

const cliProgress = require('cli-progress');

// note: you have to install this dependency manually since it's not required by cli-progress
const colors = require('ansi-colors');

// create new progress bar
const b1 = new cliProgress.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 values
b1.increment();
b1.update(20);

// stop the bar
b1.stop();

Constructor

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

const cliProgress = 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

const cliProgress = require('cli-progress');

// create new container
const multibar = new cliProgress.MultiBar({
    clearOnComplete: false,
    hideCursor: true,
    format: ' {bar} | {filename} | {value}/{total}',
}, cliProgress.Presets.shades_grey);

// add bars
const b1 = multibar.create(200, 0);
const b2 = multibar.create(1000, 0);

// control bars
b1.increment();
b2.update(20, {filename: "test1.txt"});
b1.update(20, {filename: "helloworld.txt"});

// stop all bars
multibar.stop();

Constructor

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

const cliProgress = 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: true)
  • 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

const opt = {
    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

function formatter(options, params, payload){

    // bar grows dynamically by current progress - no whitespaces are added
    const bar = options.barCompleteString.substr(0, Math.round(params.progress*options.barsize));

    // end value reached ?
    // change color to green when finished
    if (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 + ']-- ';
    }
}

const opt = {
    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 barsize
const bar = 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 barsize
const bar = 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"
const bar = 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 125
bar.update(5, {
    speed: '125'
});

// process finished
bar.stop();

Example 4 - Custom Presets

File myPreset.js

const colors = require('ansi-colors');

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

Application

const myPreset = require('./myPreset.js');

const bar = 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!

changelog (log de mudanças)

Branch 3.x

3.12.0

  • Added: option to override bar characters via instance options on multibar.create() - thanks to Araxeus on GitHub
  • Added: example howto use multibars with different bar styles
  • Bugfix: global terminal instance was not used for multibar elements which forces hard string trimming to terminal width - caused by default linewrap=true state of the terminal - thanks to emmercm on GitHub

3.11.2

  • Bugfix: disabled gracefulExit by default, because the default SIGINT/SIGTERM handlers of nodejs are removed

3.11.1

  • Bugfix: MaxListenersExceededWarning was triggered by gracefulExit handlers added in v3.11.0 - thanks to TychoTheTaco on GitHub

3.11.0

  • Added: log() convenience method the multibar to enable custom logging output on top of the progress bars during operation
  • Added: gracefulExit option (enabled by default) to stop the bars in case of SIGINT or SIGTERM - this restores most cursor settings before exiting
  • Added: progressCalculationRelative option (disabled by default) to use the startValue as offset for the progress calculation and calculate the absolute progress from the difference given by total-startValue #121
  • Added: ability to pass bar options (overrides the global options) to multibar.create
  • Bugfix: within a non-tty environment (e.g. CI/CD taskrunners) multibar.create() returns an undefined value in case noTTYOutput is not enabled #117

3.10.0

  • Changed: foreground color of preset.shades-grey is set directly by ANSI codes
  • Changed: example snippets are using ansi-colors library
  • Bugfix: removed colors dependency due to some issues with the maintainer... see Zalgo bomb

3.9.1

  • Bugfix: duration calculation doesn't work for bar restart scenarios - thanks to autlaw on GitHub

3.9.0

  • Added: exported standard formatter and format helper
  • Added: example howto use multibars in synchronous context
  • Changed: upper eta display limit to 1e7 (115days) #92

3.8.2

  • Bugfix: bar duration not stopped until all bars have finished - thanks to omjadas on GitHub

3.8.1

  • Bugfix: percentage calculation used Math.round which caused incorrect values for edge cases - thanks to OxCom on GitHub

3.8.0

  • Changed: allow to pass payload as first argument to increment() with implicit delta of 1 - thanks to ecdeveloper on GitHub
  • Changed: allow to pass payload as first argument to update() without updating bar value
  • Bugfix: formatTime option ignored due to type - thanks to omjadas on GitHub

3.7.0

  • Added: asynchronous eta update for long running processes (optional) - feature requested on GitHub
  • Added: method to trigger eta calculation without progress update

3.6.1

3.6.0

  • Added: support for custom time-format function
  • Added: support for custom bar-format function
  • Added: support for custom value-format function
  • Added: auto-padding option to enforce fixed size of values - feature requested on GitHub
  • Added: barGlue option to insert ascii escape sequences (e.g. for colorization) between the bar complete/incomplete elements - feature requested on GitHub
  • Bugfix: eta value can be negative for multibars in case the bar is alredy completed

3.5.0

3.4.0

  • Added: testsuites based on mocha - thanks to on GitHub
  • Added: automatic tests via Travis CI
  • Bugfix: Fixing issues with falsy values in format which causes remdering artifacts - thanks to on GitHub
  • Bugfix: documentation of the stream options was wrong - thanks to ehmicky on GitHub
  • Changed: updated examples/syntax of README.md - thanks to justsml on GitHub

3.3.1

  • Bugifx: synchronous update may cause unexpected behaviour on multibars - limited to single bars
  • Changed: renamed internal eta push() method to update()
  • Changed: moved internal eta calculation call into update()

3.3.0

  • Added: option to pass custom formatters as callback via options.format
  • Changed: replaced static placeholder code with generic regex (performance enhancement)

3.2.0

  • Added: emptyOnZero option to display total:0 bars as empty, not full - thanks to nickcmaynard on GitHub
  • Bugfix: removed cursor save/restore calls for multibars - clearOnComplete might not work on all environments - thanks to sayem314 onGitHub

3.1.0

  • Added: notty support (interval/schedule based output) - feature requested on GitHub
  • Added: stopOnComplete support within MultiBar - thanks to Nox-404 on GitHub
  • Changed: initial throttel time of MultiBar is controlled by fps option instead of static 500ms value
  • Bugfix: provided option didn't take precedence over the preset as in v2 - thanks to AxelTerizaki on GitHub #37

3.0.0

  • Added: multi-progressbar support - feature requested on GitHub
  • Added: option synchronousUpdate to control the synchronized redraw during update() call (default=true)
  • Changed: project split into multiple classes
  • Changed: default cli progress output is written to stdout instead of stderr

Branch 2.x

2.1.1

2.1.0

  • Added: align option to change the position of the progress bar (left, center, right) - thanks to sidneys on GitHub #22
  • Changed: ETA value of type Infinity is displayed as INF, NaN as NULL - feature requested by AxelTerizaki on GitHub #21
  • Changed: Limited the maximum ETA value to 100000s (INF is displayed in this case)
  • Changed: ETA calculation moved to own scope
  • Bugfix: example example-notty.php was broken

2.0.0

Upgrade is possible without any code modifications! requires node.js 4

  • Added: option linewrap to disable terminal line wrapping (default)
  • Changed: requires node.js >= 4
  • Changed: Native ES2015 class syntax
  • Changed: renamed application entry file to cli-progress.js
  • Changed: low-level terminal interactions are encapsulated within Terminal class
  • Changed: terminal/cursor settings are restored after progress bar stopped
  • Bugfix: used hex ascii escape sequences instaed of octals to avoid javascript errors in recent nodejs version
  • Bugfix: disabled line wrapping by default to avoid multiple line breaks on small terminals (cut on the right) - reported by puppeteer701 on GitHub #20

Branch 1.x

1.8.0

  • Added: method setTotal() to manipulate the total value within running progress-bar - feature requested by ReggaePanda on GitHub #19
  • Changed: moved example file to examples/ directory

1.7.0

  • Added: payload argument to increment() - feature requested by dsego on GitHub #18

1.6.1

  • Bugfix: roundTo parameter was not set for elapsedTime calculation which caused raw float values within formatted time strings - thanks to rekinyz on GitHub #16

1.6.0

  • Added: Additional payload data which can be used as custom-tokens within the bar - thanks to tobiasps on GitHub #15

1.5.1

  • Bugfix: Progressbar cannot be initialized to 0% - thanks to erikkallen on GitHub #13
  • Bugfix: ETA was NULL in case the progress bar is initialized with (0/0)

1.5.0

  • Added: 0 values for total/progress initialization are allowed - feature requested by jfmmm on GitHub #11

1.4.0

  • Added: Preset/Theme support. Different bar-styles can be loaded from internal library (in addition to full customization)
  • Added: Dependency colors for colorized progress bars
  • Added: Preset legacy
  • Added: Preset shades-classic
  • Added: Preset shades-grey
  • Added: Preset rect

1.3.1

  • Added: example-notty to test the behaviour of progress bar in non-interactive environments (input streams closed)
  • Bugfix: update() throws an error in non-tty environments - reported by Ognian on GitHub #9

1.3.0

  • Added: stopOnComplete option to automatically call stop() when the value reaches the total - thanks to lennym on GitHub #7

1.2.0

  • Added: increment() method to increase the current progress relatively - thanks to lennym on GitHub #6
  • Added: ETA time formatting options (mm:ss, hh:mm, ss) - thanks to lennym on GitHub #5
  • Improvement: More accurate ETA calculation using linear estimation of last N values - thanks to lennym on GitHub #4
  • Bugfix: FPS calculation error which caused performance issues - thanks to lennym on GitHub #7

1.1.2

  • Bugfix: stdout.cursorTo/stdout.clearLine is not a function; replaced by readline - thanks to remcoder on GitHub

1.1.1

  • Bugfix: Hide cursor options was enabled by default

1.1.0

  • Added: Support for synchronous operations (interval has been replaced by timeout and throttle time) - feature requested GitHub
  • Added: Synchronous Operation Example example-synchronous.js
  • Added: Option to hide the cursor options.hideCursor - default set to false
  • Changed: Improved ETA calculation

1.0.1

  • Bugfix: the bar-size is limited to options.barsize - in some (numerical) situations it can be too long (n+1)

1.0.0

  • Initial public release