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.

267 lines
8.3 KiB

4 years ago
  1. # SPDY Server for node.js
  2. [![Build Status](https://travis-ci.org/spdy-http2/node-spdy.svg?branch=master)](http://travis-ci.org/spdy-http2/node-spdy)
  3. [![NPM version](https://badge.fury.io/js/spdy.svg)](http://badge.fury.io/js/spdy)
  4. [![dependencies Status](https://david-dm.org/spdy-http2/node-spdy/status.svg?style=flat-square)](https://david-dm.org/spdy-http2/node-spdy)
  5. [![Standard - JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg?style=flat-square)](http://standardjs.com/)
  6. [![Waffle](https://img.shields.io/badge/track-waffle-blue.svg?style=flat-square)](https://waffle.io/spdy-http2/node-spdy)
  7. With this module you can create [HTTP2][0] / [SPDY][1] servers
  8. in node.js with natural http module interface and fallback to regular https
  9. (for browsers that don't support neither HTTP2, nor SPDY yet).
  10. This module named `spdy` but it [provides](https://github.com/indutny/node-spdy/issues/269#issuecomment-239014184) support for both http/2 (h2) and spdy (2,3,3.1). Also, `spdy` is compatible with Express.
  11. ## Usage
  12. ### Examples
  13. Server:
  14. ```javascript
  15. var spdy = require('spdy'),
  16. fs = require('fs');
  17. var options = {
  18. // Private key
  19. key: fs.readFileSync(__dirname + '/keys/spdy-key.pem'),
  20. // Fullchain file or cert file (prefer the former)
  21. cert: fs.readFileSync(__dirname + '/keys/spdy-fullchain.pem'),
  22. // **optional** SPDY-specific options
  23. spdy: {
  24. protocols: [ 'h2', 'spdy/3.1', ..., 'http/1.1' ],
  25. plain: false,
  26. // **optional**
  27. // Parse first incoming X_FORWARDED_FOR frame and put it to the
  28. // headers of every request.
  29. // NOTE: Use with care! This should not be used without some proxy that
  30. // will *always* send X_FORWARDED_FOR
  31. 'x-forwarded-for': true,
  32. connection: {
  33. windowSize: 1024 * 1024, // Server's window size
  34. // **optional** if true - server will send 3.1 frames on 3.0 *plain* spdy
  35. autoSpdy31: false
  36. }
  37. }
  38. };
  39. var server = spdy.createServer(options, function(req, res) {
  40. res.writeHead(200);
  41. res.end('hello world!');
  42. });
  43. server.listen(3000);
  44. ```
  45. Client:
  46. ```javascript
  47. var spdy = require('spdy');
  48. var https = require('https');
  49. var agent = spdy.createAgent({
  50. host: 'www.google.com',
  51. port: 443,
  52. // Optional SPDY options
  53. spdy: {
  54. plain: false,
  55. ssl: true,
  56. // **optional** send X_FORWARDED_FOR
  57. 'x-forwarded-for': '127.0.0.1'
  58. }
  59. });
  60. https.get({
  61. host: 'www.google.com',
  62. agent: agent
  63. }, function(response) {
  64. console.log('yikes');
  65. // Here it goes like with any other node.js HTTP request
  66. // ...
  67. // And once we're done - we may close TCP connection to server
  68. // NOTE: All non-closed requests will die!
  69. agent.close();
  70. }).end();
  71. ```
  72. Please note that if you use a custom agent, by default all connection-level
  73. errors will result in an uncaught exception. To handle these errors subscribe
  74. to the `error` event and re-emit the captured error:
  75. ```javascript
  76. var agent = spdy.createAgent({
  77. host: 'www.google.com',
  78. port: 443
  79. }).once('error', function (err) {
  80. this.emit(err);
  81. });
  82. ```
  83. #### Push streams
  84. It is possible to initiate [PUSH_PROMISE][5] to send content to clients _before_
  85. the client requests it.
  86. ```javascript
  87. spdy.createServer(options, function(req, res) {
  88. var stream = res.push('/main.js', {
  89. status: 200, // optional
  90. method: 'GET', // optional
  91. request: {
  92. accept: '*/*'
  93. },
  94. response: {
  95. 'content-type': 'application/javascript'
  96. }
  97. });
  98. stream.on('error', function() {
  99. });
  100. stream.end('alert("hello from push stream!");');
  101. res.end('<script src="/main.js"></script>');
  102. }).listen(3000);
  103. ```
  104. [PUSH_PROMISE][5] may be sent using the `push()` method on the current response
  105. object. The signature of the `push()` method is:
  106. `.push('/some/relative/url', { request: {...}, response: {...} }, callback)`
  107. Second argument contains headers for both PUSH_PROMISE and emulated response.
  108. `callback` will receive two arguments: `err` (if any error is happened) and a
  109. [Duplex][4] stream as the second argument.
  110. Client usage:
  111. ```javascript
  112. var agent = spdy.createAgent({ /* ... */ });
  113. var req = http.get({
  114. host: 'www.google.com',
  115. agent: agent
  116. }, function(response) {
  117. });
  118. req.on('push', function(stream) {
  119. stream.on('error', function(err) {
  120. // Handle error
  121. });
  122. // Read data from stream
  123. });
  124. ```
  125. NOTE: You're responsible for the `stream` object once given it in `.push()`
  126. callback or `push` event. Hence ignoring `error` event on it will result in
  127. uncaught exception and crash your program.
  128. #### Trailing headers
  129. Server usage:
  130. ```javascript
  131. function (req, res) {
  132. // Send trailing headers to client
  133. res.addTrailers({ header1: 'value1', header2: 'value2' });
  134. // On client's trailing headers
  135. req.on('trailers', function(headers) {
  136. // ...
  137. });
  138. }
  139. ```
  140. Client usage:
  141. ```javascript
  142. var req = http.request({ agent: spdyAgent, /* ... */ }).function (res) {
  143. // On server's trailing headers
  144. res.on('trailers', function(headers) {
  145. // ...
  146. });
  147. });
  148. req.write('stuff');
  149. req.addTrailers({ /* ... */ });
  150. req.end();
  151. ```
  152. #### Options
  153. All options supported by [tls][2] work with node-spdy.
  154. Additional options may be passed via `spdy` sub-object:
  155. * `plain` - if defined, server will ignore NPN and ALPN data and choose whether
  156. to use spdy or plain http by looking at first data packet.
  157. * `ssl` - if `false` and `options.plain` is `true`, `http.Server` will be used
  158. as a `base` class for created server.
  159. * `maxChunk` - if set and non-falsy, limits number of bytes sent in one DATA
  160. chunk. Setting it to non-zero value is recommended if you care about
  161. interleaving of outgoing data from multiple different streams.
  162. (defaults to 8192)
  163. * `protocols` - list of NPN/ALPN protocols to use (default is:
  164. `['h2','spdy/3.1', 'spdy/3', 'spdy/2','http/1.1', 'http/1.0']`)
  165. * `protocol` - use specific protocol if no NPN/ALPN ex In addition,
  166. * `maxStreams` - set "[maximum concurrent streams][3]" protocol option
  167. ### API
  168. API is compatible with `http` and `https` module, but you can use another
  169. function as base class for SPDYServer.
  170. ```javascript
  171. spdy.createServer(
  172. [base class constructor, i.e. https.Server],
  173. { /* keys and options */ }, // <- the only one required argument
  174. [request listener]
  175. ).listen([port], [host], [callback]);
  176. ```
  177. Request listener will receive two arguments: `request` and `response`. They're
  178. both instances of `http`'s `IncomingMessage` and `OutgoingMessage`. But three
  179. custom properties are added to both of them: `isSpdy`, `spdyVersion`. `isSpdy`
  180. is `true` when the request was processed using HTTP2/SPDY protocols, it is
  181. `false` in case of HTTP/1.1 fallback. `spdyVersion` is either of: `2`, `3`,
  182. `3.1`, or `4` (for HTTP2).
  183. #### Contributors
  184. * [Fedor Indutny](https://github.com/indutny)
  185. * [Chris Strom](https://github.com/eee-c)
  186. * [François de Metz](https://github.com/francois2metz)
  187. * [Ilya Grigorik](https://github.com/igrigorik)
  188. * [Roberto Peon](https://github.com/grmocg)
  189. * [Tatsuhiro Tsujikawa](https://github.com/tatsuhiro-t)
  190. * [Jesse Cravens](https://github.com/jessecravens)
  191. #### LICENSE
  192. This software is licensed under the MIT License.
  193. Copyright Fedor Indutny, 2015.
  194. Permission is hereby granted, free of charge, to any person obtaining a
  195. copy of this software and associated documentation files (the
  196. "Software"), to deal in the Software without restriction, including
  197. without limitation the rights to use, copy, modify, merge, publish,
  198. distribute, sublicense, and/or sell copies of the Software, and to permit
  199. persons to whom the Software is furnished to do so, subject to the
  200. following conditions:
  201. The above copyright notice and this permission notice shall be included
  202. in all copies or substantial portions of the Software.
  203. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  204. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  205. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  206. NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  207. DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  208. OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  209. USE OR OTHER DEALINGS IN THE SOFTWARE.
  210. [0]: https://http2.github.io/
  211. [1]: http://www.chromium.org/spdy
  212. [2]: http://nodejs.org/docs/latest/api/tls.html#tls.createServer
  213. [3]: https://httpwg.github.io/specs/rfc7540.html#SETTINGS_MAX_CONCURRENT_STREAMS
  214. [4]: https://iojs.org/api/stream.html#stream_class_stream_duplex
  215. [5]: https://httpwg.github.io/specs/rfc7540.html#PUSH_PROMISE