destroy.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. /*<replacement>*/
  3. var pna = require('process-nextick-args');
  4. /*</replacement>*/
  5. // undocumented cb() API, needed for core, not for public API
  6. function destroy(err, cb) {
  7. var _this = this;
  8. var readableDestroyed = this._readableState && this._readableState.destroyed;
  9. var writableDestroyed = this._writableState && this._writableState.destroyed;
  10. if (readableDestroyed || writableDestroyed) {
  11. if (cb) {
  12. cb(err);
  13. } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
  14. pna.nextTick(emitErrorNT, this, err);
  15. }
  16. return this;
  17. }
  18. // we set destroyed to true before firing error callbacks in order
  19. // to make it re-entrance safe in case destroy() is called within callbacks
  20. if (this._readableState) {
  21. this._readableState.destroyed = true;
  22. }
  23. // if this is a duplex stream mark the writable part as destroyed as well
  24. if (this._writableState) {
  25. this._writableState.destroyed = true;
  26. }
  27. this._destroy(err || null, function (err) {
  28. if (!cb && err) {
  29. pna.nextTick(emitErrorNT, _this, err);
  30. if (_this._writableState) {
  31. _this._writableState.errorEmitted = true;
  32. }
  33. } else if (cb) {
  34. cb(err);
  35. }
  36. });
  37. return this;
  38. }
  39. function undestroy() {
  40. if (this._readableState) {
  41. this._readableState.destroyed = false;
  42. this._readableState.reading = false;
  43. this._readableState.ended = false;
  44. this._readableState.endEmitted = false;
  45. }
  46. if (this._writableState) {
  47. this._writableState.destroyed = false;
  48. this._writableState.ended = false;
  49. this._writableState.ending = false;
  50. this._writableState.finished = false;
  51. this._writableState.errorEmitted = false;
  52. }
  53. }
  54. function emitErrorNT(self, err) {
  55. self.emit('error', err);
  56. }
  57. module.exports = {
  58. destroy: destroy,
  59. undestroy: undestroy
  60. };