The Readable stream interface is the abstraction for a source of data that you are reading from. In other words, data comes out of a Readable stream.
A Readable stream will not start emitting data until you indicate that you are ready to receive it.
Readable streams have two "modes": a flowing mode and a non-flowing
mode. When in flowing mode, data is read from the underlying system
and provided to your program as fast as possible. In non-flowing
mode, you must explicitly call stream.read()
to get chunks of data
out.
Examples of readable streams include:
- http responses, on the client
- http requests, on the server
- fs read streams
- [zlib streams][]
- [crypto streams][]
- [tcp sockets][]
- [child process stdout and stderr][]
- [process.stdin][]
var http = require("http")
var server = http.createServer(function (req, res) {
// req is a HttpRequest which is Readable
var body = ''
// Readable streams emit 'data' events
req.on('data', function (chunk) {
body += chunk
})
// once ended you know you have entire body
req.on('end', function () {
var data = JSON.parse(body)
// do stuff
})
})
When a chunk of data can be read from the stream, it will emit a
'readable'
event.
In some cases, listening for a 'readable'
event will cause some data
to be read into the internal buffer from the underlying system, if it
hadn't already.
var readable = getReadableStreamSomehow();
readable.on('readable', function() {
// there is some data to read now
})
Once the internal buffer is drained, a readable
event will fire
again when more data is available.