index.js 2.2 KB

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