Last active
January 17, 2024 20:27
-
-
Save nuxlli/b425344b92ac1ff99c74 to your computer and use it in GitHub Desktop.
Multiple bars example with npm `progress`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ProgressBar = require('progress'); | |
function Multibar(stream) { | |
this.stream = stream || process.stderr; | |
this.cursor = 0; | |
this.bars = []; | |
this.terminates = 0; | |
} | |
Multibar.prototype = { | |
newBar: function(schema, options) { | |
options.stream = this.stream; | |
var bar = new ProgressBar(schema, options); | |
this.bars.push(bar); | |
var index = this.bars.length - 1; | |
// alloc line | |
this.move(index); | |
this.stream.write('\n'); | |
this.cursor ++; | |
// replace original | |
var self = this; | |
bar.otick = bar.tick; | |
bar.oterminate = bar.terminate; | |
bar.tick = function(value, options) { | |
self.tick(index, value, options); | |
} | |
bar.terminate = function() { | |
self.terminates++; | |
if (self.terminates == self.bars.length) { | |
self.terminate(); | |
} | |
} | |
return bar; | |
}, | |
terminate: function() { | |
this.move(this.bars.length); | |
this.stream.clearLine(); | |
this.stream.cursorTo(0); | |
}, | |
move: function(index) { | |
if (!this.stream.isTTY) return; | |
this.stream.moveCursor(0, index - this.cursor); | |
this.cursor = index; | |
}, | |
tick: function(index, value, options) { | |
var bar = this.bars[index]; | |
if (bar) { | |
this.move(index); | |
bar.otick(value, options); | |
} | |
} | |
} | |
var mbars = new Multibar(); | |
var bars = []; | |
function addBar() { | |
bars.push(mbars.newBar(' :title [:bar] :percent', { | |
complete: '=' | |
, incomplete: ' ' | |
, width: 30 | |
, total: 100 | |
})); | |
return bars[bars.length - 1]; | |
} | |
function forward() { | |
for (var i = 0; i < bars.length; i++) { | |
bars[i].tick(1, { title: 'forward: ' }); | |
} | |
if (bars[0].curr > 60) { | |
addBar().tick(bars[0].curr); | |
backward(); | |
} else { | |
setTimeout(forward, 20); | |
} | |
} | |
function backward() { | |
for (var i = 0; i < bars.length; i++) { | |
bars[i].tick(-1, { title: 'backward: ' }); | |
} | |
if (bars[0].curr == 0) { | |
mbars.terminate(); | |
console.log("End all"); | |
} else { | |
setTimeout(backward, 20); | |
} | |
} | |
for(var i = 0; i < 5; i++) { | |
addBar(); | |
} | |
forward(); |
multi-progress is now a package on npm
Yay!
The links of the multi-progress
are as follows:
@pitaj I wonder if you'd consider updating multi-progress
. It has a dependency on an older version of progress
which has a bug. Thanks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
multi-progress is now a package on npm
Yay!