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'); + } + }); };