* Wraps a `WebSocket` in a duplex stream. * * @param {WebSocket} ws The `WebSocket` to wrap * @param {Object} [options] The options for the `Duplex` constructor * @return {Duplex} The duplex stream * @public
(ws, options)
| 49 | * @public |
| 50 | */ |
| 51 | function createWebSocketStream(ws, options) { |
| 52 | let terminateOnDestroy = true; |
| 53 | |
| 54 | const duplex = new Duplex({ |
| 55 | ...options, |
| 56 | autoDestroy: false, |
| 57 | emitClose: false, |
| 58 | objectMode: false, |
| 59 | writableObjectMode: false |
| 60 | }); |
| 61 | |
| 62 | ws.on('message', function message(msg, isBinary) { |
| 63 | const data = |
| 64 | !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; |
| 65 | |
| 66 | if (!duplex.push(data)) ws.pause(); |
| 67 | }); |
| 68 | |
| 69 | ws.once('error', function error(err) { |
| 70 | if (duplex.destroyed) return; |
| 71 | |
| 72 | // Prevent `ws.terminate()` from being called by `duplex._destroy()`. |
| 73 | // |
| 74 | // - If the `'error'` event is emitted before the `'open'` event, then |
| 75 | // `ws.terminate()` is a noop as no socket is assigned. |
| 76 | // - Otherwise, the error is re-emitted by the listener of the `'error'` |
| 77 | // event of the `Receiver` object. The listener already closes the |
| 78 | // connection by calling `ws.close()`. This allows a close frame to be |
| 79 | // sent to the other peer. If `ws.terminate()` is called right after this, |
| 80 | // then the close frame might not be sent. |
| 81 | terminateOnDestroy = false; |
| 82 | duplex.destroy(err); |
| 83 | }); |
| 84 | |
| 85 | ws.once('close', function close() { |
| 86 | if (duplex.destroyed) return; |
| 87 | |
| 88 | duplex.push(null); |
| 89 | }); |
| 90 | |
| 91 | duplex._destroy = function (err, callback) { |
| 92 | if (ws.readyState === ws.CLOSED) { |
| 93 | callback(err); |
| 94 | process.nextTick(emitClose, duplex); |
| 95 | return; |
| 96 | } |
| 97 | |
| 98 | let called = false; |
| 99 | |
| 100 | ws.once('error', function error(err) { |
| 101 | called = true; |
| 102 | callback(err); |
| 103 | }); |
| 104 | |
| 105 | ws.once('close', function close() { |
| 106 | if (!called) callback(err); |
| 107 | process.nextTick(emitClose, duplex); |
| 108 | }); |