Skip to content

Commit aed2e69

Browse files
Make sure to finalize the request properly (node-fetch#432)
Unfortunately, I could not write a test case that allows testing the bug in node-fetch#428. Credits to Roman Zaharenkov <ZaharenkovRoman@gmail.com> for discovering this long-standing bug and proposing a first version of the fix. Co-authored-by: Roman Zaharenkov <ZaharenkovRoman@gmail.com> Fixes: node-fetch#428
1 parent d522036 commit aed2e69

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

src/index.js

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,18 +47,23 @@ export default function fetch(url, opts) {
4747
const req = send(options);
4848
let reqTimeout;
4949

50+
function finalize() {
51+
req.abort();
52+
clearTimeout(reqTimeout);
53+
}
54+
5055
if (request.timeout) {
5156
req.once('socket', socket => {
5257
reqTimeout = setTimeout(() => {
53-
req.abort();
5458
reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
59+
finalize();
5560
}, request.timeout);
5661
});
5762
}
5863

5964
req.on('error', err => {
60-
clearTimeout(reqTimeout);
6165
reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
66+
finalize();
6267
});
6368

6469
req.on('response', res => {
@@ -78,6 +83,7 @@ export default function fetch(url, opts) {
7883
switch (request.redirect) {
7984
case 'error':
8085
reject(new FetchError(`redirect mode is set to error: ${request.url}`, 'no-redirect'));
86+
finalize();
8187
return;
8288
case 'manual':
8389
// node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
@@ -94,6 +100,7 @@ export default function fetch(url, opts) {
94100
// HTTP-redirect fetch step 5
95101
if (request.counter >= request.follow) {
96102
reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
103+
finalize();
97104
return;
98105
}
99106

@@ -111,7 +118,9 @@ export default function fetch(url, opts) {
111118

112119
// HTTP-redirect fetch step 9
113120
if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
114-
reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'))
121+
reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
122+
finalize();
123+
return;
115124
}
116125

117126
// HTTP-redirect fetch step 11
@@ -123,6 +132,7 @@ export default function fetch(url, opts) {
123132

124133
// HTTP-redirect fetch step 15
125134
resolve(fetch(new Request(locationURL, requestOpts)));
135+
finalize();
126136
return;
127137
}
128138
}

0 commit comments

Comments
 (0)