From 51ba87265b4c371ed0310c13a73ac937666d8ee0 Mon Sep 17 00:00:00 2001 From: James Martin Date: Wed, 10 Aug 2016 14:11:04 -0400 Subject: [PATCH] feature(interrupt): added feature to interrupt the bar and display a message --- Readme.md | 17 +++++++++++++++++ examples/interrupt.js | 18 ++++++++++++++++++ lib/node-progress.js | 23 ++++++++++++++++++++++- 3 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 examples/interrupt.js diff --git a/Readme.md b/Readme.md index 344e38c..3bb6e9e 100644 --- a/Readme.md +++ b/Readme.md @@ -119,6 +119,23 @@ The above example result in a progress bar like the one below. downloading [===== ] 29% 3.7s ``` +### Interrupt + +To display a message during progress bar execution, use `interupt()` +```javascript +var ProgressBar = require('progress'); + +var bar = new ProgressBar(':bar :current/:total', { total: 10 }); +var timer = setInterval(function () { + bar.tick(); + if (bar.complete) { + clearInterval(timer); + } else if (bar.curr === 5) { + bar.interrupt('this message appears above the progress bar\ncurrent progress is ' + bar.curr + '/' + bar.total); + } +}, 1000); +``` + You can see more examples in the `examples` folder. ## License diff --git a/examples/interrupt.js b/examples/interrupt.js new file mode 100644 index 0000000..8cfd5a8 --- /dev/null +++ b/examples/interrupt.js @@ -0,0 +1,18 @@ +/** + * An example to show a progress bar being interrupted, + * displaying messages above the bar while keeping the + * progress intact + */ + +var ProgressBar = require('progress'); + +var bar = new ProgressBar(':bar :current/:total', { total: 10 }); +var timer = setInterval(function () { + bar.tick(); + if (bar.complete) { + clearInterval(timer); + } else if (bar.curr === 5 || bar.curr === 8) { + bar.interrupt('interrupt: current progress is ' + bar.curr + '/' + bar.total); + } +}, 1000); + diff --git a/lib/node-progress.js b/lib/node-progress.js index 3f97e36..f62d6e8 100644 --- a/lib/node-progress.js +++ b/lib/node-progress.js @@ -180,6 +180,25 @@ ProgressBar.prototype.update = function (ratio, tokens) { this.tick(delta, tokens); }; +/** + * "interrupt" the progress bar and write a message above it. + * @param {string} message The message to write. + * @api public + */ + +ProgressBar.prototype.interrupt = function (message) { + // clear the current line + this.stream.clearLine(); + // move the cursor to the start of the line + this.stream.cursorTo(0); + // write the message text + this.stream.write(message); + // terminate the line after writing the message + this.stream.write('\n'); + // re-display the progress bar with its lastDraw + this.stream.write(this.lastDraw); +}; + /** * Terminates a progress bar. * @@ -190,5 +209,7 @@ ProgressBar.prototype.terminate = function () { if (this.clear) { this.stream.clearLine(); this.stream.cursorTo(0); - } else this.stream.write('\n'); + } else { + this.stream.write('\n'); + } };