sindresorhus / get-stream

Get a stream as a string, Buffer, ArrayBuffer or array
MIT License
341 stars 33 forks source link

Premature close error is not thrown when http request is aborted #38

Closed tiagonapoli closed 4 years ago

tiagonapoli commented 4 years ago

When using get-stream to get data from a http response and the request associated with it is aborted an error is not thrown:

const handleWithGetStream = async (res) => {
    try {
        const data = await getStream(res)
        console.log(data)
    } catch(err) {
        console.log(err)
    }
}

const handleWithFinished = async (res) => {
    try {
        let data = ''
        res.on('data', (buf) => data += buf.toString())
        await promisify(finished)(res)
        console.log(data)
    } catch(err) {
        console.log(err)
    }
}

const req = http.get('http://localhost:3000', (res) => {
    console.log(res.statusCode)
    handleWithGetStream(res)
    setTimeout(() => req.abort(), 100)
})

Using stream.finished it properly throws:

Error [ERR_STREAM_PREMATURE_CLOSE]: Premature close
    at IncomingMessage.onclose (internal/streams/end-of-stream.js:75:15)
    at IncomingMessage.emit (events.js:315:20)
    at Socket.socketCloseListener (_http_client.js:383:11)
    at Socket.emit (events.js:327:22)
    at TCP.<anonymous> (net.js:674:12) {
  code: 'ERR_STREAM_PREMATURE_CLOSE'
}

But using getStream it finishes successfully.

I have setup an repo reproducing this behavior https://github.com/tiagonapoli/get-stream-test

Further info: Node version: 12.18.0 get-stream version: 5.1.0