node-progress.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. /*!
  2. * node-progress
  3. * Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>
  4. * MIT Licensed
  5. */
  6. /**
  7. * Expose `ProgressBar`.
  8. */
  9. exports = module.exports = ProgressBar;
  10. /**
  11. * Initialize a `ProgressBar` with the given `fmt` string and `options` or
  12. * `total`.
  13. *
  14. * Options:
  15. *
  16. * - `curr` current completed index
  17. * - `total` total number of ticks to complete
  18. * - `width` the displayed width of the progress bar defaulting to total
  19. * - `stream` the output stream defaulting to stderr
  20. * - `head` head character defaulting to complete character
  21. * - `complete` completion character defaulting to "="
  22. * - `incomplete` incomplete character defaulting to "-"
  23. * - `renderThrottle` minimum time between updates in milliseconds defaulting to 16
  24. * - `callback` optional function to call when the progress bar completes
  25. * - `clear` will clear the progress bar upon termination
  26. *
  27. * Tokens:
  28. *
  29. * - `:bar` the progress bar itself
  30. * - `:current` current tick number
  31. * - `:total` total ticks
  32. * - `:elapsed` time elapsed in seconds
  33. * - `:percent` completion percentage
  34. * - `:eta` eta in seconds
  35. * - `:rate` rate of ticks per second
  36. *
  37. * @param {string} fmt
  38. * @param {object|number} options or total
  39. * @api public
  40. */
  41. function ProgressBar(fmt, options) {
  42. this.stream = options.stream || process.stderr;
  43. if (typeof(options) == 'number') {
  44. var total = options;
  45. options = {};
  46. options.total = total;
  47. } else {
  48. options = options || {};
  49. if ('string' != typeof fmt) throw new Error('format required');
  50. if ('number' != typeof options.total) throw new Error('total required');
  51. }
  52. this.fmt = fmt;
  53. this.curr = options.curr || 0;
  54. this.total = options.total;
  55. this.width = options.width || this.total;
  56. this.clear = options.clear
  57. this.chars = {
  58. complete : options.complete || '=',
  59. incomplete : options.incomplete || '-',
  60. head : options.head || (options.complete || '=')
  61. };
  62. this.renderThrottle = options.renderThrottle !== 0 ? (options.renderThrottle || 16) : 0;
  63. this.lastRender = -Infinity;
  64. this.callback = options.callback || function () {};
  65. this.tokens = {};
  66. this.lastDraw = '';
  67. }
  68. /**
  69. * "tick" the progress bar with optional `len` and optional `tokens`.
  70. *
  71. * @param {number|object} len or tokens
  72. * @param {object} tokens
  73. * @api public
  74. */
  75. ProgressBar.prototype.tick = function(len, tokens){
  76. if (len !== 0)
  77. len = len || 1;
  78. // swap tokens
  79. if ('object' == typeof len) tokens = len, len = 1;
  80. if (tokens) this.tokens = tokens;
  81. // start time for eta
  82. if (0 == this.curr) this.start = new Date;
  83. this.curr += len
  84. // try to render
  85. this.render();
  86. // progress complete
  87. if (this.curr >= this.total) {
  88. this.render(undefined, true);
  89. this.complete = true;
  90. this.terminate();
  91. this.callback(this);
  92. return;
  93. }
  94. };
  95. /**
  96. * Method to render the progress bar with optional `tokens` to place in the
  97. * progress bar's `fmt` field.
  98. *
  99. * @param {object} tokens
  100. * @api public
  101. */
  102. ProgressBar.prototype.render = function (tokens, force) {
  103. force = force !== undefined ? force : false;
  104. if (tokens) this.tokens = tokens;
  105. if (!this.stream.isTTY) return;
  106. var now = Date.now();
  107. var delta = now - this.lastRender;
  108. if (!force && (delta < this.renderThrottle)) {
  109. return;
  110. } else {
  111. this.lastRender = now;
  112. }
  113. var ratio = this.curr / this.total;
  114. ratio = Math.min(Math.max(ratio, 0), 1);
  115. var percent = Math.floor(ratio * 100);
  116. var incomplete, complete, completeLength;
  117. var elapsed = new Date - this.start;
  118. var eta = (percent == 100) ? 0 : elapsed * (this.total / this.curr - 1);
  119. var rate = this.curr / (elapsed / 1000);
  120. /* populate the bar template with percentages and timestamps */
  121. var str = this.fmt
  122. .replace(':current', this.curr)
  123. .replace(':total', this.total)
  124. .replace(':elapsed', isNaN(elapsed) ? '0.0' : (elapsed / 1000).toFixed(1))
  125. .replace(':eta', (isNaN(eta) || !isFinite(eta)) ? '0.0' : (eta / 1000)
  126. .toFixed(1))
  127. .replace(':percent', percent.toFixed(0) + '%')
  128. .replace(':rate', Math.round(rate));
  129. /* compute the available space (non-zero) for the bar */
  130. var availableSpace = Math.max(0, this.stream.columns - str.replace(':bar', '').length);
  131. if(availableSpace && process.platform === 'win32'){
  132. availableSpace = availableSpace - 1;
  133. }
  134. var width = Math.min(this.width, availableSpace);
  135. /* TODO: the following assumes the user has one ':bar' token */
  136. completeLength = Math.round(width * ratio);
  137. complete = Array(Math.max(0, completeLength + 1)).join(this.chars.complete);
  138. incomplete = Array(Math.max(0, width - completeLength + 1)).join(this.chars.incomplete);
  139. /* add head to the complete string */
  140. if(completeLength > 0)
  141. complete = complete.slice(0, -1) + this.chars.head;
  142. /* fill in the actual progress bar */
  143. str = str.replace(':bar', complete + incomplete);
  144. /* replace the extra tokens */
  145. if (this.tokens) for (var key in this.tokens) str = str.replace(':' + key, this.tokens[key]);
  146. if (this.lastDraw !== str) {
  147. this.stream.cursorTo(0);
  148. this.stream.write(str);
  149. this.stream.clearLine(1);
  150. this.lastDraw = str;
  151. }
  152. };
  153. /**
  154. * "update" the progress bar to represent an exact percentage.
  155. * The ratio (between 0 and 1) specified will be multiplied by `total` and
  156. * floored, representing the closest available "tick." For example, if a
  157. * progress bar has a length of 3 and `update(0.5)` is called, the progress
  158. * will be set to 1.
  159. *
  160. * A ratio of 0.5 will attempt to set the progress to halfway.
  161. *
  162. * @param {number} ratio The ratio (between 0 and 1 inclusive) to set the
  163. * overall completion to.
  164. * @api public
  165. */
  166. ProgressBar.prototype.update = function (ratio, tokens) {
  167. var goal = Math.floor(ratio * this.total);
  168. var delta = goal - this.curr;
  169. this.tick(delta, tokens);
  170. };
  171. /**
  172. * "interrupt" the progress bar and write a message above it.
  173. * @param {string} message The message to write.
  174. * @api public
  175. */
  176. ProgressBar.prototype.interrupt = function (message) {
  177. // clear the current line
  178. this.stream.clearLine();
  179. // move the cursor to the start of the line
  180. this.stream.cursorTo(0);
  181. // write the message text
  182. this.stream.write(message);
  183. // terminate the line after writing the message
  184. this.stream.write('\n');
  185. // re-display the progress bar with its lastDraw
  186. this.stream.write(this.lastDraw);
  187. };
  188. /**
  189. * Terminates a progress bar.
  190. *
  191. * @api public
  192. */
  193. ProgressBar.prototype.terminate = function () {
  194. if (this.clear) {
  195. if (this.stream.clearLine) {
  196. this.stream.clearLine();
  197. this.stream.cursorTo(0);
  198. }
  199. } else {
  200. this.stream.write('\n');
  201. }
  202. };