Skip to content

Instantly share code, notes, and snippets.

@Raynos
Created September 30, 2012 01:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Raynos/3805596 to your computer and use it in GitHub Desktop.
Save Raynos/3805596 to your computer and use it in GitHub Desktop.
HTTP Stream

HTTP Stream

A Stream of HTTP req/res pairs

Example

var HttpStream = require("http-stream")
    , chain = require("chain-stream")
    , request = require("request")

var server = chain(HttpStream().listen(8080))

server
    .filter(route("/hello.json"))
    .forEach(function (dup) {
        dup.setHeader("content-type", "application/json")
        dup.end(JSON.stringify({ msg: "hello" }))
    })

server
    .filter(route("/plaintext"))
    .forEach(function (dup) {
        dup.setHeader("content-type", "text/plain")
        dup.end("I like text/plain")
    })

server
    .filter(route("/"))
    .filter(method("GET"))
    .forEach(function (dup) {
        dup.setHeader("content-type", "text/html")

        chain(
            request("http://me.iriscouch.com/db", {
                json: true
            }))
            .map(function (chunk) {
                return "<html><head>cool</head><body>" + chunk.index +
                    "</body></html>"
            })
            .pipe(dup)
    })

function route(path) {
    /* router implementation. A single matching on dup.url */
}

function method(methodName) {
    return function (dup) {
        return dup.method === methodName
    }
}
var http = require("http")
, ReadStream = require("read-stream")
, httpDuplex = require("http-duplex")
, reemit = require("re-emitter").reemit
, serverEvents = [
"request"
, "connection"
, "close"
, "checkContinue"
, "connect"
, "upgrade"
, "clientError"
]
, serverMethods = [
"listen"
, "close"
]
function HttpStream() {
var queue = ReadStream()
, server = http.createServer(handler)
, stream = queue.stream
server.on("close", queue.end)
serverMethods.forEach(function (methodName) {
stream[methodName] = method
function method() {
server[methodName].apply(server, arguments)
return stream
}
})
reemit(server, stream, serverEvents)
return stream
function handler(req, res) {
var dup = httpDuplex(req, res)
queue.push(dup)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment