Skip to content

Commit

Permalink
Fix Cannot call end error when request returns a Writable
Browse files Browse the repository at this point in the history
  • Loading branch information
szmarczak committed Jul 12, 2021
1 parent c0b5346 commit 226cc39
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
6 changes: 6 additions & 0 deletions source/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,12 @@ export default class Request extends Duplex implements RequestEvents<Request> {
}

this._request.end((error?: Error | null) => {
// The request has been destroyed before `_final` finished.
// See https://github.com/nodejs/node/issues/39356
if ((this._request as any)._writableState?.errored) {
return;
}

if (!error) {
this._bodySize = this._uploadedSize;

Expand Down
16 changes: 15 additions & 1 deletion test/stream.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {promisify} from 'util';
import fs from 'fs';
import {Agent as HttpAgent} from 'http';
import stream, {PassThrough as PassThroughStream, Readable as ReadableStream} from 'stream';
import stream, {PassThrough as PassThroughStream, Readable as ReadableStream, Writable} from 'stream';
import {Readable as Readable2} from 'readable-stream';
import test from 'ava';
import {Handler} from 'express';
Expand Down Expand Up @@ -497,6 +497,20 @@ test('accepts readable-stream as body', withServer, async (t, server, got) => {
t.is(response.body, 'ok');
});

test('prevents `Cannot call end` error', async t => {
const stream = got.stream('https://example.com', {
request: () => new Writable({
final() {}
}) as any,
timeout: {
request: 1
}
});

const error: RequestError = await pEvent(stream, 'error');
t.is(error.code, 'ETIMEDOUT');
});

if (Number.parseInt(process.versions.node.split('.')[0]!, 10) <= 12) {
test('does not emit end event on error', withServer, async (t, server, got) => {
server.get('/', infiniteHandler);
Expand Down

0 comments on commit 226cc39

Please sign in to comment.