diff --git a/examples/multipletokens.js b/examples/multipletokens.js new file mode 100644 index 0000000..8560610 --- /dev/null +++ b/examples/multipletokens.js @@ -0,0 +1,19 @@ +'use strict'; +const ProgressBar = require('../'); + +const bar = new ProgressBar("Multiple tokens contain current::current current::current total::total elapsed::elapseds etas::etas rate::rate percent::percent [:bar] current::current total::total elapsed::elapseds etas::etas rate::rate percent::percent, hello world!", + { total: 100 }); +let timerBar = setInterval( () => { + bar.tick(); + if (bar.complete) { + clearInterval(timerBar); + } +}, 10); + +const baz = new ProgressBar('The two bar [:bar] and [:bar], hello world!', {total: 100}); +let timerBaz = setInterval( () => { + baz.tick(); + if (baz.complete) { + clearInterval(timerBaz); + } +}, 10); \ No newline at end of file diff --git a/lib/node-progress.js b/lib/node-progress.js index 8eb0740..5b90866 100644 --- a/lib/node-progress.js +++ b/lib/node-progress.js @@ -137,18 +137,20 @@ ProgressBar.prototype.render = function (tokens, force) { var eta = (percent == 100) ? 0 : elapsed * (this.total / this.curr - 1); var rate = this.curr / (elapsed / 1000); - /* populate the bar template with percentages and timestamps */ + /** + * populate the bar template with percentages and timestamps. + * replace multiple tokens, for example, the curr of tokens replace multiple ':current' . + */ var str = this.fmt - .replace(':current', this.curr) - .replace(':total', this.total) - .replace(':elapsed', isNaN(elapsed) ? '0.0' : (elapsed / 1000).toFixed(1)) - .replace(':eta', (isNaN(eta) || !isFinite(eta)) ? '0.0' : (eta / 1000) - .toFixed(1)) - .replace(':percent', percent.toFixed(0) + '%') - .replace(':rate', Math.round(rate)); + .replaceAll(':current', this.curr) + .replaceAll(':total', this.total) + .replaceAll(':elapsed', isNaN(elapsed) ? '0.0' : (elapsed / 1000).toFixed(1)) + .replaceAll(':eta', (isNaN(eta) || !isFinite(eta)) ? '0.0' : (eta / 1000).toFixed(1)) + .replaceAll(':percent', percent.toFixed(0) + '%') + .replaceAll(':rate', Math.round(rate)); /* compute the available space (non-zero) for the bar */ - var availableSpace = Math.max(0, this.stream.columns - str.replace(':bar', '').length); + var availableSpace = Math.max(0, this.stream.columns - str.replaceAll(':bar', '').length); if(availableSpace && process.platform === 'win32'){ availableSpace = availableSpace - 1; } @@ -165,10 +167,10 @@ ProgressBar.prototype.render = function (tokens, force) { complete = complete.slice(0, -1) + this.chars.head; /* fill in the actual progress bar */ - str = str.replace(':bar', complete + incomplete); + str = str.replaceAll(':bar', complete + incomplete); /* replace the extra tokens */ - if (this.tokens) for (var key in this.tokens) str = str.replace(':' + key, this.tokens[key]); + if (this.tokens) for (var key in this.tokens) str = str.replaceAll(':' + key, this.tokens[key]); if (this.lastDraw !== str) { this.stream.cursorTo(0);