UNPKG

1.84 kBJavaScriptView Raw
1'use strict';
2
3// from https://gist.github.com/nuxlli/b425344b92ac1ff99c74
4// with some modifications & additions
5
6const ProgressBar = require('progress');
7
8const emptyObj = {
9 newBar() {
10 return {
11 tick() {},
12 terminate() {},
13 update() {},
14 render() {},
15 };
16 },
17 terminate() {},
18 move() {},
19 tick() {},
20 update() {},
21 isTTY: false,
22};
23
24function MultiProgress(stream) {
25 const multi = Object.create(MultiProgress.prototype);
26 multi.stream = stream || process.stderr;
27
28 if (!multi.stream.isTTY)
29 return emptyObj;
30
31
32 multi.cursor = 0;
33 multi.bars = [];
34 multi.terminates = 0;
35
36 return multi;
37}
38
39MultiProgress.prototype = {
40 newBar(schema, options) {
41 options.stream = this.stream;
42 const bar = new ProgressBar(schema, options);
43 this.bars.push(bar);
44 const index = this.bars.length - 1;
45
46 // alloc line
47 this.move(index);
48 this.stream.write('\n');
49 this.cursor += 1;
50
51 // replace original
52 const self = this;
53 bar.otick = bar.tick;
54 bar.oterminate = bar.terminate;
55 bar.oupdate = bar.update;
56 bar.tick = function tick(value, op) {
57 self.tick(index, value, op);
58 };
59 bar.terminate = function terminate() {
60 self.terminates += 1;
61 if (self.terminates === self.bars.length)
62 self.terminate();
63 };
64 bar.update = function update(value, op) {
65 self.update(index, value, op);
66 };
67
68 return bar;
69 },
70
71 terminate() {
72 this.move(this.bars.length);
73 this.stream.clearLine();
74 this.stream.cursorTo(0);
75 },
76
77 move(index) {
78 this.stream.moveCursor(0, index - this.cursor);
79 this.cursor = index;
80 },
81
82 tick(index, value, options) {
83 const bar = this.bars[index];
84 if (bar) {
85 this.move(index);
86 bar.otick(value, options);
87 }
88 },
89
90 update(index, value, options) {
91 const bar = this.bars[index];
92 if (bar) {
93 this.move(index);
94 bar.oupdate(value, options);
95 }
96 },
97};
98
99module.exports = MultiProgress;