index.js 967 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. module.exports = (stream, throwError) => {
  3. return new Promise((resolve, reject) => {
  4. if (typeof stream.resume !== 'function') {
  5. return resolve();
  6. }
  7. // unpipe it
  8. stream.unpipe && stream.unpipe();
  9. // enable resume first
  10. stream.resume();
  11. if (stream._readableState && stream._readableState.ended) {
  12. return resolve();
  13. }
  14. if (!stream.readable || stream.destroyed) {
  15. return resolve();
  16. }
  17. function cleanup() {
  18. stream.removeListener('end', onEnd);
  19. stream.removeListener('close', onEnd);
  20. stream.removeListener('error', onError);
  21. }
  22. function onEnd() {
  23. cleanup();
  24. resolve();
  25. }
  26. function onError(err) {
  27. cleanup();
  28. // don't throw error by default
  29. if (throwError) {
  30. reject(err);
  31. } else {
  32. resolve();
  33. }
  34. }
  35. stream.on('end', onEnd);
  36. stream.on('close', onEnd);
  37. stream.on('error', onError);
  38. });
  39. };