index.js 889 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. 'use strict';
  2. const Duplex = require('stream').Duplex;
  3. const kCallback = Symbol('Callback');
  4. const kOtherSide = Symbol('Other');
  5. class DuplexSocket extends Duplex {
  6. constructor(options) {
  7. super(options);
  8. this[kCallback] = null;
  9. this[kOtherSide] = null;
  10. }
  11. _read() {
  12. const callback = this[kCallback];
  13. if (callback) {
  14. this[kCallback] = null;
  15. callback();
  16. }
  17. }
  18. _write(chunk, encoding, callback) {
  19. this[kOtherSide][kCallback] = callback;
  20. this[kOtherSide].push(chunk);
  21. }
  22. _final(callback) {
  23. this[kOtherSide].on('end', callback);
  24. this[kOtherSide].push(null);
  25. }
  26. }
  27. class DuplexPair {
  28. constructor(options) {
  29. this.socket1 = new DuplexSocket(options);
  30. this.socket2 = new DuplexSocket(options);
  31. this.socket1[kOtherSide] = this.socket2;
  32. this.socket2[kOtherSide] = this.socket1;
  33. }
  34. }
  35. module.exports = DuplexPair;