Skip to content

Commit

Permalink
Prevent hanging when stream is not readable
Browse files Browse the repository at this point in the history
  • Loading branch information
ziyofun authored and dougwilson committed Feb 17, 2022
1 parent 5e59d0a commit 64156ae
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 0 deletions.
1 change: 1 addition & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ unreleased
==========

* Prevent loss of async hooks context
* Prevent hanging when stream is not readable
* deps: http-errors@2.0.0
- deps: depd@2.0.0
- deps: statuses@2.0.1
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,10 @@ This error will occur when the given stream has an encoding set on it, making it
a decoded stream. The stream should not have an encoding set and is expected to
emit `Buffer` objects.

#### stream.not.readable

This error will occur when the given stream is not readable.

## Examples

### Simple Express example
Expand Down
6 changes: 6 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,12 @@ function readStream (stream, encoding, length, limit, callback) {
}))
}

if (typeof stream.readable !== 'undefined' && !stream.readable) {
return done(createError(500, 'stream is not readable', {
type: 'stream.not.readable'
}))
}

var received = 0
var decoder

Expand Down
40 changes: 40 additions & 0 deletions test/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,46 @@ describe('using http streams', function () {
})
})

it('should throw if stream is not readable', function (done) {
var server = http.createServer(function onRequest (req, res) {
getRawBody(req, { length: req.headers['content-length'] }, function (err) {
if (err) {
req.resume()
res.statusCode = 500
res.end(err.message)
return
}

getRawBody(req, { length: req.headers['content-length'] }, function (err) {
if (err) {
res.statusCode = 500
res.end('[' + err.type + '] ' + err.message)
} else {
res.statusCode = 200
res.end()
}
})
})
})

server.listen(function onListen () {
var addr = server.address()
var client = http.request({ method: 'POST', port: addr.port })

client.end('hello, world!')

client.on('response', function onResponse (res) {
getRawBody(res, { encoding: true }, function (err, str) {
server.close(function onClose () {
assert.ifError(err)
assert.strictEqual(str, '[stream.not.readable] stream is not readable')
done()
})
})
})
})
})

it('should throw if connection ends', function (done) {
var socket
var server = http.createServer(function onRequest (req, res) {
Expand Down

0 comments on commit 64156ae

Please sign in to comment.