Skip to content

Instantly share code, notes, and snippets.

@Raynos Raynos/x.md Secret
Created Feb 20, 2013

Embed
What would you like to do?

read-stream

Base class for readable streams

Example push model

var ReadStream = require("read-stream")

var socket = connect(...)
var stream = ReadStream(function onread(push, cb) {
    socket.readStart()
})

socket.ondata = function (chunk) {
    var needsMore = stream.push(chunk)

    if (!needsMore) {
        socket.readStop()
    }
}

socket.onend = function () {
    stream.push(null)
}

socket.onerror = function (err) {
    stream.push(err)
}

stream.pipe(process.stdout)

Example pull model

var ReadStream = require("read-stream")

var source = db.cursor(...)
var stream = ReadStream(function onread(push, cb) {
    cursor.nextObject(consume)

    function consume(err, item) {
        var needsMore = push(err || item)

        if (needsMore) {
            cursor.nextObject(consume)
        }
    }
})

stream.pipe(process.stdout)

Example array

var from = require("read-stream/array")
var stream = from(["one", "two"])

stream.pipe(process.stdout)

Example callback

var callback = require("read-stream/callback")

var stream = callback(function (cb) {
    fs.readFile(someUri, cb)
})

stream.pipe(process.stdout)

Installation

npm install read-stream

Contributors

  • Raynos

MIT Licenced

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.