Skip to content

Commit

Permalink
improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
Vadim Demedes committed Jun 1, 2017
1 parent a504bc0 commit 7af37a0
Showing 1 changed file with 18 additions and 10 deletions.
28 changes: 18 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const getBodySize = opts => {

return new Promise((resolve, reject) => {
if (opts.headers['content-length']) {
resolve(opts.headers['content-length']);
resolve(Number(opts.headers['content-length']));
return;
}

Expand Down Expand Up @@ -73,7 +73,7 @@ const getBodySize = opts => {
return;
}

if (body && Buffer.isBuffer(body._buffer)) {
if (isStream(body) && Buffer.isBuffer(body._buffer)) {
resolve(body._buffer.length);
return;
}
Expand Down Expand Up @@ -165,6 +165,7 @@ function requestAsEventEmitter(opts) {

const percent = downloadBodySize ? downloaded / downloadBodySize : 0;

// Let flush() be responsible for emitting the last event
if (percent < 1) {
ee.emit('downloadProgress', {
percent,
Expand All @@ -189,6 +190,7 @@ function requestAsEventEmitter(opts) {

progressStream.redirectUrls = redirects;

// Simulate response stream by copying its props
Object.keys(res).forEach(key => {
if (!key.startsWith('_')) {
progressStream[key] = res[key];
Expand Down Expand Up @@ -241,10 +243,14 @@ function requestAsEventEmitter(opts) {
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;
}
Expand All @@ -268,17 +274,17 @@ function requestAsEventEmitter(opts) {
});
};

getBodySize(opts)
.then(size => {
uploadBodySize = size;
setImmediate(() => {
getBodySize(opts)
.then(size => {
uploadBodySize = size;

setImmediate(() => {
get(opts);
})
.catch(err => {
ee.emit('error', err);
});
})
.catch(err => {
ee.emit('error', err);
});
});

return ee;
}
Expand Down Expand Up @@ -514,6 +520,8 @@ function normalizeArguments(url, opts) {
headers['content-length'] = length;
}

// Convert buffer to stream to receive upload progress events
// see https://github.com/sindresorhus/got/pull/322
if (Buffer.isBuffer(body)) {
opts.body = intoStream(body);
opts.body._buffer = body;
Expand Down

0 comments on commit 7af37a0

Please sign in to comment.