stream.js 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. 'use strict';
  2. const { Duplex } = require('stream');
  3. /**
  4. * Emits the `'close'` event on a stream.
  5. *
  6. * @param {Duplex} stream The stream.
  7. * @private
  8. */
  9. function emitClose(stream) {
  10. stream.emit('close');
  11. }
  12. /**
  13. * The listener of the `'end'` event.
  14. *
  15. * @private
  16. */
  17. function duplexOnEnd() {
  18. if (!this.destroyed && this._writableState.finished) {
  19. this.destroy();
  20. }
  21. }
  22. /**
  23. * The listener of the `'error'` event.
  24. *
  25. * @param {Error} err The error
  26. * @private
  27. */
  28. function duplexOnError(err) {
  29. this.removeListener('error', duplexOnError);
  30. this.destroy();
  31. if (this.listenerCount('error') === 0) {
  32. // Do not suppress the throwing behavior.
  33. this.emit('error', err);
  34. }
  35. }
  36. /**
  37. * Wraps a `WebSocket` in a duplex stream.
  38. *
  39. * @param {WebSocket} ws The `WebSocket` to wrap
  40. * @param {Object} [options] The options for the `Duplex` constructor
  41. * @return {Duplex} The duplex stream
  42. * @public
  43. */
  44. function createWebSocketStream(ws, options) {
  45. let terminateOnDestroy = true;
  46. const duplex = new Duplex({
  47. ...options,
  48. autoDestroy: false,
  49. emitClose: false,
  50. objectMode: false,
  51. writableObjectMode: false
  52. });
  53. ws.on('message', function message(msg, isBinary) {
  54. const data =
  55. !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
  56. if (!duplex.push(data)) ws.pause();
  57. });
  58. ws.once('error', function error(err) {
  59. if (duplex.destroyed) return;
  60. // Prevent `ws.terminate()` from being called by `duplex._destroy()`.
  61. //
  62. // - If the `'error'` event is emitted before the `'open'` event, then
  63. // `ws.terminate()` is a noop as no socket is assigned.
  64. // - Otherwise, the error is re-emitted by the listener of the `'error'`
  65. // event of the `Receiver` object. The listener already closes the
  66. // connection by calling `ws.close()`. This allows a close frame to be
  67. // sent to the other peer. If `ws.terminate()` is called right after this,
  68. // then the close frame might not be sent.
  69. terminateOnDestroy = false;
  70. duplex.destroy(err);
  71. });
  72. ws.once('close', function close() {
  73. if (duplex.destroyed) return;
  74. duplex.push(null);
  75. });
  76. duplex._destroy = function (err, callback) {
  77. if (ws.readyState === ws.CLOSED) {
  78. callback(err);
  79. process.nextTick(emitClose, duplex);
  80. return;
  81. }
  82. let called = false;
  83. ws.once('error', function error(err) {
  84. called = true;
  85. callback(err);
  86. });
  87. ws.once('close', function close() {
  88. if (!called) callback(err);
  89. process.nextTick(emitClose, duplex);
  90. });
  91. if (terminateOnDestroy) ws.terminate();
  92. };
  93. duplex._final = function (callback) {
  94. if (ws.readyState === ws.CONNECTING) {
  95. ws.once('open', function open() {
  96. duplex._final(callback);
  97. });
  98. return;
  99. }
  100. // If the value of the `_socket` property is `null` it means that `ws` is a
  101. // client websocket and the handshake failed. In fact, when this happens, a
  102. // socket is never assigned to the websocket. Wait for the `'error'` event
  103. // that will be emitted by the websocket.
  104. if (ws._socket === null) return;
  105. if (ws._socket._writableState.finished) {
  106. callback();
  107. if (duplex._readableState.endEmitted) duplex.destroy();
  108. } else {
  109. ws._socket.once('finish', function finish() {
  110. // `duplex` is not destroyed here because the `'end'` event will be
  111. // emitted on `duplex` after this `'finish'` event. The EOF signaling
  112. // `null` chunk is, in fact, pushed when the websocket emits `'close'`.
  113. callback();
  114. });
  115. ws.close();
  116. }
  117. };
  118. duplex._read = function () {
  119. if (ws.isPaused) ws.resume();
  120. };
  121. duplex._write = function (chunk, encoding, callback) {
  122. if (ws.readyState === ws.CONNECTING) {
  123. ws.once('open', function open() {
  124. duplex._write(chunk, encoding, callback);
  125. });
  126. return;
  127. }
  128. ws.send(chunk, callback);
  129. };
  130. duplex.on('end', duplexOnEnd);
  131. duplex.on('error', duplexOnError);
  132. return duplex;
  133. }
  134. module.exports = createWebSocketStream;