Skip to content

Commit

Permalink
Check req.connection exists before attaching event listeners (#429)
Browse files Browse the repository at this point in the history
  • Loading branch information
lukechilds authored and sindresorhus committed Jan 9, 2018
1 parent 4f5e6bf commit 30c39bc
Showing 1 changed file with 27 additions and 25 deletions.
52 changes: 27 additions & 25 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 30c39bc

Please sign in to comment.