Streaming and mutation API for HTTP responses.
The basic idea is to build request for HTTP Responses.
This whole package is still beta.
var server = httpcreateServervar f = fscreateReadStream'file.js'if requrl === '/test.js' return fpiperesponsepiperes
When pipeing files to
response it will lookup the mime type and set the propert content-type header for whatever file extension you send it.
var server = httpcreateServerif requrl === '/' return responsehtml'<html>Hello World</html>'piperesif requrl === '/sitemap.html'var f = fscreateReadStream'sitemap'return fpiperesponsehtmlpiperesif requrl === '/something.json' return responsejsontest:1piperesif requrl === '/something.txt' return responsetxt'some test'piperes
r.error'Uh Oh!' 501piperes
In addition, errors emitted on the stream piped to
response will be passed through the same API and are accesssible in
gzip keys in an options object are used for compression.
var server = httpcreateServervar f = fscreateReadStream'file.js'if requrl === '/file.js' return fpiperesponsecompress:reqpiperes
You can pass an HTTP Request object and the best compression, if any, will be chosen for you. Alternatively you can pass
"deflate" to forcce compression of the response stream.
This compression option is compatible with every other feature in
response and will work whether you do file streaming, html, json, or even using views. When passing a view, string or buffer to
response the second argument is used as the options object.
var server = httpcreateServerif requrl === '/' return responsehtml'<html>Nope</html>' compress:reqpiperes
response also has an extended version of node core's HTTP Response API.
All headers setting and checking is done caseless while preserving the original casing when first set. This way you never accidentally send two of the same header but can still support broken clients that check for specific caseing.
Set the statusCode property to send the HTTP status code. This is a non-destructive way to send the status code.
var r = responserstatusCode = 500rhtml'<html>Error</html>'
Defaults to clobbering (overwritting) existing values but when disabled will concatenate values.
Set multiple headers by passing an object.
rsetHeader'x-blah': 'somehost' 'x-blah2': 'anotherhost.com'
You can retreive a header by its key, use this method instead of directly accessing the headers object to avoid caseing constraints.
Check if a header is already set. If one is set the header key will be returned (which is important because it may have different caseing).
if e return cbecbnull '<html>' + data + '</html>'var server = httpcreateServervar r = responseviewrpiperesif requrl === '/test1' return rhtml'test'
This is how you would easily support something like a template system. TODO: example.
Mad props to @marak who handed over the "response" package in npm that he registered way back in the day.