index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. 'use strict';
  2. var through2 = require('through2');
  3. var EE = require('events').EventEmitter;
  4. var gutil = require('gulp-util');
  5. function removeDefaultHandler(stream, event) {
  6. var found = false;
  7. stream.listeners(event).forEach(function (item) {
  8. if (item.name === 'on' + event) {
  9. found = item;
  10. this.removeListener(event, item);
  11. }
  12. }, stream);
  13. return found;
  14. }
  15. function wrapPanicOnErrorHandler(stream) {
  16. var oldHandler = removeDefaultHandler(stream, 'error');
  17. if (oldHandler) {
  18. stream.on('error', function onerror2(er) {
  19. if (EE.listenerCount(stream, 'error') === 1) {
  20. this.removeListener('error', onerror2);
  21. oldHandler.call(stream, er);
  22. }
  23. });
  24. }
  25. }
  26. function defaultErrorHandler(error) {
  27. // onerror2 and this handler
  28. if (EE.listenerCount(this, 'error') < 3) {
  29. gutil.log(
  30. gutil.colors.cyan('Plumber') + gutil.colors.red(' found unhandled error:\n'),
  31. error.toString()
  32. );
  33. }
  34. }
  35. function plumber(opts) {
  36. opts = opts || {};
  37. if (typeof opts === 'function') {
  38. opts = {errorHandler: opts};
  39. }
  40. var through = through2.obj();
  41. through._plumber = true;
  42. if (opts.errorHandler !== false) {
  43. through.errorHandler = (typeof opts.errorHandler === 'function') ?
  44. opts.errorHandler :
  45. defaultErrorHandler;
  46. }
  47. function patchPipe(stream) {
  48. if (stream.pipe2) {
  49. wrapPanicOnErrorHandler(stream);
  50. stream._pipe = stream._pipe || stream.pipe;
  51. stream.pipe = stream.pipe2;
  52. stream._plumbed = true;
  53. }
  54. }
  55. through.pipe2 = function pipe2(dest) {
  56. if (!dest) {
  57. throw new gutil.PluginError('plumber', 'Can\'t pipe to undefined');
  58. }
  59. this._pipe.apply(this, arguments);
  60. if (dest._unplumbed) {
  61. return dest;
  62. }
  63. removeDefaultHandler(this, 'error');
  64. if (dest._plumber) {
  65. return dest;
  66. }
  67. dest.pipe2 = pipe2;
  68. // Patching pipe method
  69. if (opts.inherit !== false) {
  70. patchPipe(dest);
  71. }
  72. // Placing custom on error handler
  73. if (this.errorHandler) {
  74. dest.errorHandler = this.errorHandler;
  75. dest.on('error', this.errorHandler.bind(dest));
  76. }
  77. dest._plumbed = true;
  78. return dest;
  79. };
  80. patchPipe(through);
  81. return through;
  82. }
  83. module.exports = plumber;
  84. module.exports.stop = function () {
  85. var through = through2.obj();
  86. through._unplumbed = true;
  87. return through;
  88. };