You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

323 lines
7.8 KiB

7 years ago
  1. <img src="https://github.com/flatiron/union/raw/master/union.png" />
  2. # Synopsis
  3. A hybrid streaming middleware kernel backwards compatible with connect.
  4. # Motivation
  5. The advantage to streaming middlewares is that they do not require buffering the entire stream in order to execute their function.
  6. # Status
  7. [![Build Status](https://secure.travis-ci.org/flatiron/union.png)](http://travis-ci.org/flatiron/union)
  8. # Installation
  9. There are a few ways to use `union`. Install the library using npm. You can add it to your `package.json` file as a dependancy
  10. ```bash
  11. $ [sudo] npm install union
  12. ```
  13. ## Usage
  14. Union's request handling is [connect](https://github.com/senchalabs/connect)-compatible, meaning that all existing connect middlewares should work out-of-the-box with union.
  15. **(Union 0.3.x is compatible with connect >= 2.1.0, [Extensively Tested](https://github.com/pksunkara/connect-union))**
  16. In addition, the response object passed to middlewares listens for a "next" event, which is equivalent to calling `next()`. Flatiron middlewares are written in this manner, meaning they are not reverse-compatible with connect.
  17. ### A simple case
  18. ``` js
  19. var fs = require('fs'),
  20. union = require('../lib'),
  21. director = require('director');
  22. var router = new director.http.Router();
  23. var server = union.createServer({
  24. before: [
  25. function (req, res) {
  26. var found = router.dispatch(req, res);
  27. if (!found) {
  28. res.emit('next');
  29. }
  30. }
  31. ]
  32. });
  33. router.get(/foo/, function () {
  34. this.res.writeHead(200, { 'Content-Type': 'text/plain' })
  35. this.res.end('hello world\n');
  36. });
  37. router.post(/foo/, { stream: true }, function () {
  38. var req = this.req,
  39. res = this.res,
  40. writeStream;
  41. writeStream = fs.createWriteStream(Date.now() + '-foo.txt');
  42. req.pipe(writeStream);
  43. writeStream.on('close', function () {
  44. res.writeHead(200, { 'Content-Type': 'text/plain' });
  45. res.end('wrote to a stream!');
  46. });
  47. });
  48. server.listen(9090);
  49. console.log('union with director running on 9090');
  50. ```
  51. To demonstrate the code, we use [director](https://github.com/flatiron/director). A light-weight, Client AND Server side URL-Router for Node.js and Single Page Apps!
  52. ### A case with connect
  53. Code based on connect
  54. ```js
  55. var connect = require('connect')
  56. , http = require('http');
  57. var app = connect()
  58. .use(connect.favicon())
  59. .use(connect.logger('dev'))
  60. .use(connect.static('public'))
  61. .use(connect.directory('public'))
  62. .use(connect.cookieParser('my secret here'))
  63. .use(connect.session())
  64. .use(function (req, res) {
  65. res.end('Hello from Connect!\n');
  66. });
  67. http.createServer(app).listen(3000);
  68. ```
  69. Code based on union
  70. ```js
  71. var connect = require('connect')
  72. , union = require('union');
  73. var server = union.createServer({
  74. buffer: false,
  75. before: [
  76. connect.favicon(),
  77. connect.logger('dev'),
  78. connect.static('public'),
  79. connect.directory('public'),
  80. connect.cookieParser('my secret here'),
  81. connect.session(),
  82. function (req, res) {
  83. res.end('Hello from Connect!\n');
  84. },
  85. ]
  86. }).listen(3000);
  87. ```
  88. ### SPDY enabled server example
  89. # API
  90. ## union Static Members
  91. ### createServer(options)
  92. The `options` object is required. Options include:
  93. Specification
  94. ```
  95. function createServer(options)
  96. @param options {Object}
  97. An object literal that represents the configuration for the server.
  98. @option before {Array}
  99. The `before` value is an array of middlewares, which are used to route and serve incoming
  100. requests. For instance, in the example, `favicon` is a middleware which handles requests
  101. for `/favicon.ico`.
  102. @option after {Array}
  103. The `after` value is an array of functions that return stream filters,
  104. which are applied after the request handlers in `options.before`.
  105. Stream filters inherit from `union.ResponseStream`, which implements the
  106. Node.js core streams api with a bunch of other goodies.
  107. @option limit {Object}
  108. (optional) A value, passed to internal instantiations of `union.BufferedStream`.
  109. @option https {Object}
  110. (optional) A value that specifies the certificate and key necessary to create an instance of
  111. `https.Server`.
  112. @option spdy {Object}
  113. (optional) A value that specifies the certificate and key necessary to create an instance of
  114. `spdy.Server`.
  115. @option headers {Object}
  116. (optional) An object representing a set of headers to set in every outgoing response
  117. ```
  118. Example
  119. ```js
  120. var server = union.createServer({
  121. before: [
  122. favicon('./favicon.png'),
  123. function (req, res) {
  124. var found = router.dispatch(req, res);
  125. if (!found) {
  126. res.emit('next');
  127. }
  128. }
  129. ]
  130. });
  131. ```
  132. An example of the `https` or `spdy` option.
  133. ``` js
  134. {
  135. cert: 'path/to/cert.pem',
  136. key: 'path/to/key.pem',
  137. ca: 'path/to/ca.pem'
  138. }
  139. ```
  140. An example of the `headers` option.
  141. ``` js
  142. {
  143. 'x-powered-by': 'your-sweet-application v10.9.8'
  144. }
  145. ```
  146. ## Error Handling
  147. Error handler is similiar to middlware but takes an extra argument for error at the beginning.
  148. ```js
  149. var handle = function (err, req, res) {
  150. res.statusCode = err.status;
  151. res.end(req.headers);
  152. };
  153. var server = union.createServer({
  154. onError: handle,
  155. before: [
  156. favicon('./favicon.png'),
  157. function (req, res) {
  158. var found = router.dispatch(req, res);
  159. if (!found) {
  160. res.emit('next');
  161. }
  162. }
  163. ]
  164. });
  165. ```
  166. ## BufferedStream Constructor
  167. This constructor inherits from `Stream` and can buffer data up to `limit` bytes. It also implements `pause` and `resume` methods.
  168. Specification
  169. ```
  170. function BufferedStream(limit)
  171. @param limit {Number}
  172. the limit for which the stream can be buffered
  173. ```
  174. Example
  175. ```js
  176. var bs = union.BufferedStream(n);
  177. ```
  178. ## HttpStream Constructor
  179. This constructor inherits from `union.BufferedStream` and returns a stream with these extra properties:
  180. Specification
  181. ```
  182. function HttpStream()
  183. ```
  184. Example
  185. ```js
  186. var hs = union.HttpStream();
  187. ```
  188. ## HttpStream Instance Members
  189. ### url
  190. The url from the request.
  191. Example
  192. ```js
  193. httpStream.url = '';
  194. ```
  195. ### headers
  196. The HTTP headers associated with the stream.
  197. Example
  198. ```js
  199. httpStream.headers = '';
  200. ```
  201. ### method
  202. The HTTP method ("GET", "POST", etc).
  203. Example
  204. ```js
  205. httpStream.method = 'POST';
  206. ```
  207. ### query
  208. The querystring associated with the stream (if applicable).
  209. Example
  210. ```js
  211. httpStream.query = '';
  212. ```
  213. ## ResponseStream Constructor
  214. This constructor inherits from `union.HttpStream`, and is additionally writeable. Union supplies this constructor as a basic response stream middleware from which to inherit.
  215. Specification
  216. ```
  217. function ResponseStream()
  218. ```
  219. Example
  220. ```js
  221. var rs = union.ResponseStream();
  222. ```
  223. # Tests
  224. All tests are written with [vows][0] and should be run with [npm][1]:
  225. ``` bash
  226. $ npm test
  227. ```
  228. # Licence
  229. (The MIT License)
  230. Copyright (c) 2010-2012 Charlie Robbins & the Contributors
  231. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  232. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  233. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  234. [0]: http://vowsjs.org
  235. [1]: http://npmjs.org