Skip to content

Instantly share code, notes, and snippets.

@Raynos
Created July 16, 2013 01:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Raynos/6004985 to your computer and use it in GitHub Desktop.
Save Raynos/6004985 to your computer and use it in GitHub Desktop.

Class: stream.Readable

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:

Example usage

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
    })
})

Event: 'readable'

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment