From 30c39bc1c3042a80ed3f6752677e0ab42cb1ca98 Mon Sep 17 00:00:00 2001 From: Luke Childs Date: Tue, 9 Jan 2018 15:41:38 +0700 Subject: [PATCH] Check req.connection exists before attaching event listeners (#429) --- index.js | 52 +++++++++++++++++++++++++++------------------------- 1 file changed, 27 insertions(+), 25 deletions(-) diff --git a/index.js b/index.js index 89aa28343..6c82aa881 100644 --- a/index.js +++ b/index.js @@ -227,33 +227,35 @@ function requestAsEventEmitter(opts) { total: uploadBodySize }); - req.connection.once('connect', () => { - const uploadEventFrequency = 150; - - progressInterval = setInterval(() => { - const lastUploaded = uploaded; - const headersSize = Buffer.byteLength(req._header); - uploaded = req.connection.bytesWritten - headersSize; - - // Prevent the known issue of `bytesWritten` being larger than body size - if (uploadBodySize && uploaded > uploadBodySize) { - uploaded = uploadBodySize; - } + if (req.connection) { + req.connection.once('connect', () => { + const uploadEventFrequency = 150; + + progressInterval = setInterval(() => { + const lastUploaded = uploaded; + const headersSize = Buffer.byteLength(req._header); + uploaded = req.connection.bytesWritten - headersSize; + + // Prevent the known issue of `bytesWritten` being larger than body size + if (uploadBodySize && uploaded > uploadBodySize) { + uploaded = uploadBodySize; + } - // Don't emit events with unchanged progress and - // prevent last event from being emitted, because - // it's emitted when `response` is emitted - if (uploaded === lastUploaded || uploaded === uploadBodySize) { - return; - } + // Don't emit events with unchanged progress and + // prevent last event from being emitted, because + // it's emitted when `response` is emitted + if (uploaded === lastUploaded || uploaded === uploadBodySize) { + return; + } - ee.emit('uploadProgress', { - percent: uploadBodySize ? uploaded / uploadBodySize : 0, - transferred: uploaded, - total: uploadBodySize - }); - }, uploadEventFrequency); - }); + ee.emit('uploadProgress', { + percent: uploadBodySize ? uploaded / uploadBodySize : 0, + transferred: uploaded, + total: uploadBodySize + }); + }, uploadEventFrequency); + }); + } }); if (opts.gotTimeout) {