_stream_duplex.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // a duplex stream is just a stream that is both readable and writable.
  2. // Since JS doesn't have multiple prototypal inheritance, this class
  3. // prototypally inherits from Readable, and then parasitically from
  4. // Writable.
  5. 'use strict';
  6. /*<replacement>*/
  7. var objectKeys = Object.keys || function (obj) {
  8. var keys = [];
  9. for (var key in obj) {
  10. keys.push(key);
  11. }return keys;
  12. };
  13. /*</replacement>*/
  14. module.exports = Duplex;
  15. /*<replacement>*/
  16. var processNextTick = require('process-nextick-args');
  17. /*</replacement>*/
  18. /*<replacement>*/
  19. var util = require('core-util-is');
  20. util.inherits = require('inherits');
  21. /*</replacement>*/
  22. var Readable = require('./_stream_readable');
  23. var Writable = require('./_stream_writable');
  24. util.inherits(Duplex, Readable);
  25. var keys = objectKeys(Writable.prototype);
  26. for (var v = 0; v < keys.length; v++) {
  27. var method = keys[v];
  28. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  29. }
  30. function Duplex(options) {
  31. if (!(this instanceof Duplex)) return new Duplex(options);
  32. Readable.call(this, options);
  33. Writable.call(this, options);
  34. if (options && options.readable === false) this.readable = false;
  35. if (options && options.writable === false) this.writable = false;
  36. this.allowHalfOpen = true;
  37. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  38. this.once('end', onend);
  39. }
  40. // the no-half-open enforcer
  41. function onend() {
  42. // if we allow half-open state, or if the writable side ended,
  43. // then we're ok.
  44. if (this.allowHalfOpen || this._writableState.ended) return;
  45. // no more data can be written.
  46. // But allow more writes to happen in this tick.
  47. processNextTick(onEndNT, this);
  48. }
  49. function onEndNT(self) {
  50. self.end();
  51. }
  52. function forEach(xs, f) {
  53. for (var i = 0, l = xs.length; i < l; i++) {
  54. f(xs[i], i);
  55. }
  56. }