index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. 'use strict';
  2. var throttle = require('throttleit');
  3. function requestProgress(request, options) {
  4. var reporter;
  5. var onResponse;
  6. var delayTimer;
  7. var delayCompleted;
  8. var totalSize;
  9. var previousReceivedSize;
  10. var receivedSize = 0;
  11. var state = {};
  12. options = options || {};
  13. options.throttle = options.throttle == null ? 1000 : options.throttle;
  14. options.delay = options.delay || 0;
  15. // Throttle the progress report function
  16. reporter = throttle(function () {
  17. // If the received size is the same, do not report
  18. if (previousReceivedSize === receivedSize) {
  19. return;
  20. }
  21. // Update received
  22. previousReceivedSize = receivedSize;
  23. state.received = receivedSize;
  24. // Update percentage
  25. // Note that the totalSize might available
  26. state.percent = totalSize ? Math.round(receivedSize / totalSize * 100) : null;
  27. request.emit('progress', state);
  28. }, options.throttle);
  29. // On response handler
  30. onResponse = function (response) {
  31. totalSize = Number(response.headers['content-length']);
  32. receivedSize = 0;
  33. // Note that the totalSize might available
  34. state.totalSize = totalSize || null;
  35. // Delay the progress report
  36. delayCompleted = false;
  37. delayTimer = setTimeout(function () {
  38. delayCompleted = true;
  39. delayTimer = null;
  40. }, options.delay);
  41. };
  42. request
  43. .on('request', function () {
  44. receivedSize = 0;
  45. })
  46. .on('response', onResponse)
  47. .on('data', function (data) {
  48. receivedSize += data.length;
  49. if (delayCompleted) {
  50. reporter();
  51. }
  52. })
  53. .on('end', function () {
  54. if (delayTimer) {
  55. clearTimeout(delayTimer);
  56. delayTimer = null;
  57. }
  58. });
  59. // If we already got a response, call the on response handler
  60. if (request.response) {
  61. onResponse(request.response);
  62. }
  63. return request;
  64. }
  65. module.exports = requestProgress;