duplex.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import {inherits} from 'util';
  2. import {nextTick} from 'process';
  3. import {Readable} from './readable';
  4. import {Writable} from './writable';
  5. inherits(Duplex, Readable);
  6. var keys = Object.keys(Writable.prototype);
  7. for (var v = 0; v < keys.length; v++) {
  8. var method = keys[v];
  9. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  10. }
  11. export default Duplex;
  12. export function Duplex(options) {
  13. if (!(this instanceof Duplex)) return new Duplex(options);
  14. Readable.call(this, options);
  15. Writable.call(this, options);
  16. if (options && options.readable === false) this.readable = false;
  17. if (options && options.writable === false) this.writable = false;
  18. this.allowHalfOpen = true;
  19. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  20. this.once('end', onend);
  21. }
  22. // the no-half-open enforcer
  23. function onend() {
  24. // if we allow half-open state, or if the writable side ended,
  25. // then we're ok.
  26. if (this.allowHalfOpen || this._writableState.ended) return;
  27. // no more data can be written.
  28. // But allow more writes to happen in this tick.
  29. nextTick(onEndNT, this);
  30. }
  31. function onEndNT(self) {
  32. self.end();
  33. }