From db3f16f5fa9f42082eec963e2c90c6e2ecbbce11 Mon Sep 17 00:00:00 2001 From: fent <933490+fent@users.noreply.github.com> Date: Sat, 14 Nov 2020 15:24:23 -0700 Subject: [PATCH] fix: only emit `close` on last request emitting `close` early can affect the internal readable stream state. previously, this was emitted on chunks and reconnects. --- lib/index.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/index.js b/lib/index.js index d8925e68..4570fa34 100644 --- a/lib/index.js +++ b/lib/index.js @@ -51,11 +51,19 @@ const createStream = options => { const pipeAndSetEvents = (req, stream, end) => { // Forward events from the request to the stream. [ - 'abort', 'request', 'response', 'error', 'close', 'redirect', 'retry', 'reconnect', + 'abort', 'request', 'response', 'error', 'redirect', 'retry', 'reconnect', ].forEach(event => { req.prependListener(event, stream.emit.bind(stream, event)); }); req.pipe(stream, { end }); + + // Emit `close` only when stream is already destroyed, in case there are multiple requests + // due to playlists, chunking, and reconnects. + req.on('close', () => { + if (stream.destroyed) { + stream.emit('close'); + } + }); };