Skip to content

Commit

Permalink
move stream readable check test to http.js and update readme file
Browse files Browse the repository at this point in the history
  • Loading branch information
ziyofun committed Mar 26, 2018
1 parent 58c7fac commit e59940d
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 13 deletions.
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 not readable, it may be a request parsed by other middleware before.

## Examples

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

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

var received = 0
Expand Down
22 changes: 22 additions & 0 deletions test/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,28 @@ 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) {
assert.ifError(err)

getRawBody(req, { length: req.headers['content-length'] }, function (err) {
assert.ok(err)
assert.equal(err.status, 500)
assert.equal(err.type, 'stream.not.readable')
assert.equal(err.message, 'stream should be readable')
done()
})
})
})

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

it('should throw if connection ends', function (done) {
var socket
var server = http.createServer(function onRequest (req, res) {
Expand Down
11 changes: 0 additions & 11 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,17 +112,6 @@ describe('Raw Body', function () {
})
})

it('should throw if stream is not readable', function (done) {
var stream = new Readable()
stream.readable = false

getRawBody(stream, function (err, buf) {
assert.equal(err.status, 500)
assert.equal(err.message, 'stream should be readable')
done()
})
})

it('should work with an empty stream', function (done) {
var stream = new Readable()
stream.push(null)
Expand Down

0 comments on commit e59940d

Please sign in to comment.