| 48 | */ |
| 49 | class JSStreamSocket extends Socket { |
| 50 | constructor(stream) { |
| 51 | const handle = new JSStream(); |
| 52 | handle.close = (cb) => { |
| 53 | debug('close'); |
| 54 | this.doClose(cb); |
| 55 | }; |
| 56 | // Inside of the following functions, `this` refers to the handle |
| 57 | // and `this[owner_symbol]` refers to this JSStreamSocket instance. |
| 58 | handle.isClosing = isClosing; |
| 59 | handle.onreadstart = onreadstart; |
| 60 | handle.onreadstop = onreadstop; |
| 61 | handle.onshutdown = onshutdown; |
| 62 | handle.onwrite = onwrite; |
| 63 | |
| 64 | stream.pause(); |
| 65 | stream.on('error', (err) => this.emit('error', err)); |
| 66 | const ondata = (chunk) => { |
| 67 | if (typeof chunk === 'string' || |
| 68 | stream.readableObjectMode === true) { |
| 69 | // Make sure that no further `data` events will happen. |
| 70 | stream.pause(); |
| 71 | stream.removeListener('data', ondata); |
| 72 | |
| 73 | this.emit('error', new ERR_STREAM_WRAP()); |
| 74 | return; |
| 75 | } |
| 76 | |
| 77 | debug('data', chunk.length); |
| 78 | if (this._handle) |
| 79 | this._handle.readBuffer(chunk); |
| 80 | }; |
| 81 | stream.on('data', ondata); |
| 82 | stream.once('end', () => { |
| 83 | debug('end'); |
| 84 | if (this._handle) |
| 85 | this._handle.emitEOF(); |
| 86 | }); |
| 87 | // Some `Stream` don't pass `hasError` parameters when closed. |
| 88 | stream.once('close', () => { |
| 89 | // Errors emitted from `stream` have also been emitted to this instance |
| 90 | // so that we don't pass errors to `destroy()` again. |
| 91 | this.destroy(); |
| 92 | }); |
| 93 | |
| 94 | super({ handle, manualStart: true }); |
| 95 | this.stream = stream; |
| 96 | this[kCurrentWriteRequest] = null; |
| 97 | this[kCurrentShutdownRequest] = null; |
| 98 | this[kPendingShutdownRequest] = null; |
| 99 | this[kPendingClose] = false; |
| 100 | this.readable = stream.readable; |
| 101 | this.writable = stream.writable; |
| 102 | |
| 103 | // Start reading. |
| 104 | this.read(0); |
| 105 | } |
| 106 | |
| 107 | // Allow legacy requires in the test suite to keep working: |