1# HTTP/2 2<!-- YAML 3added: v8.4.0 4changes: 5 - version: v10.10.0 6 pr-url: https://github.com/nodejs/node/pull/22466 7 description: HTTP/2 is now Stable. Previously, it had been Experimental. 8--> 9<!--introduced_in=v8.4.0--> 10 11> Stability: 2 - Stable 12 13The `http2` module provides an implementation of the [HTTP/2][] protocol. It 14can be accessed using: 15 16```js 17const http2 = require('http2'); 18``` 19 20## Core API 21 22The Core API provides a low-level interface designed specifically around 23support for HTTP/2 protocol features. It is specifically *not* designed for 24compatibility with the existing [HTTP/1][] module API. However, 25the [Compatibility API][] is. 26 27The `http2` Core API is much more symmetric between client and server than the 28`http` API. For instance, most events, like `'error'`, `'connect'` and 29`'stream'`, can be emitted either by client-side code or server-side code. 30 31### Server-side example 32 33The following illustrates a simple HTTP/2 server using the Core API. 34Since there are no browsers known that support 35[unencrypted HTTP/2][HTTP/2 Unencrypted], the use of 36[`http2.createSecureServer()`][] is necessary when communicating 37with browser clients. 38 39```js 40const http2 = require('http2'); 41const fs = require('fs'); 42 43const server = http2.createSecureServer({ 44 key: fs.readFileSync('localhost-privkey.pem'), 45 cert: fs.readFileSync('localhost-cert.pem') 46}); 47server.on('error', (err) => console.error(err)); 48 49server.on('stream', (stream, headers) => { 50 // stream is a Duplex 51 stream.respond({ 52 'content-type': 'text/html', 53 ':status': 200 54 }); 55 stream.end('<h1>Hello World</h1>'); 56}); 57 58server.listen(8443); 59``` 60 61To generate the certificate and key for this example, run: 62 63```bash 64openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \ 65 -keyout localhost-privkey.pem -out localhost-cert.pem 66``` 67 68### Client-side example 69 70The following illustrates an HTTP/2 client: 71 72```js 73const http2 = require('http2'); 74const fs = require('fs'); 75const client = http2.connect('https://localhost:8443', { 76 ca: fs.readFileSync('localhost-cert.pem') 77}); 78client.on('error', (err) => console.error(err)); 79 80const req = client.request({ ':path': '/' }); 81 82req.on('response', (headers, flags) => { 83 for (const name in headers) { 84 console.log(`${name}: ${headers[name]}`); 85 } 86}); 87 88req.setEncoding('utf8'); 89let data = ''; 90req.on('data', (chunk) => { data += chunk; }); 91req.on('end', () => { 92 console.log(`\n${data}`); 93 client.close(); 94}); 95req.end(); 96``` 97 98### Class: Http2Session 99<!-- YAML 100added: v8.4.0 101--> 102 103* Extends: {EventEmitter} 104 105Instances of the `http2.Http2Session` class represent an active communications 106session between an HTTP/2 client and server. Instances of this class are *not* 107intended to be constructed directly by user code. 108 109Each `Http2Session` instance will exhibit slightly different behaviors 110depending on whether it is operating as a server or a client. The 111`http2session.type` property can be used to determine the mode in which an 112`Http2Session` is operating. On the server side, user code should rarely 113have occasion to work with the `Http2Session` object directly, with most 114actions typically taken through interactions with either the `Http2Server` or 115`Http2Stream` objects. 116 117User code will not create `Http2Session` instances directly. Server-side 118`Http2Session` instances are created by the `Http2Server` instance when a 119new HTTP/2 connection is received. Client-side `Http2Session` instances are 120created using the `http2.connect()` method. 121 122#### Http2Session and Sockets 123 124Every `Http2Session` instance is associated with exactly one [`net.Socket`][] or 125[`tls.TLSSocket`][] when it is created. When either the `Socket` or the 126`Http2Session` are destroyed, both will be destroyed. 127 128Because of the specific serialization and processing requirements imposed 129by the HTTP/2 protocol, it is not recommended for user code to read data from 130or write data to a `Socket` instance bound to a `Http2Session`. Doing so can 131put the HTTP/2 session into an indeterminate state causing the session and 132the socket to become unusable. 133 134Once a `Socket` has been bound to an `Http2Session`, user code should rely 135solely on the API of the `Http2Session`. 136 137#### Event: 'close' 138<!-- YAML 139added: v8.4.0 140--> 141 142The `'close'` event is emitted once the `Http2Session` has been destroyed. Its 143listener does not expect any arguments. 144 145#### Event: 'connect' 146<!-- YAML 147added: v8.4.0 148--> 149 150* `session` {Http2Session} 151* `socket` {net.Socket} 152 153The `'connect'` event is emitted once the `Http2Session` has been successfully 154connected to the remote peer and communication may begin. 155 156User code will typically not listen for this event directly. 157 158#### Event: 'error' 159<!-- YAML 160added: v8.4.0 161--> 162 163* `error` {Error} 164 165The `'error'` event is emitted when an error occurs during the processing of 166an `Http2Session`. 167 168#### Event: 'frameError' 169<!-- YAML 170added: v8.4.0 171--> 172 173* `type` {integer} The frame type. 174* `code` {integer} The error code. 175* `id` {integer} The stream id (or `0` if the frame isn't associated with a 176 stream). 177 178The `'frameError'` event is emitted when an error occurs while attempting to 179send a frame on the session. If the frame that could not be sent is associated 180with a specific `Http2Stream`, an attempt to emit `'frameError'` event on the 181`Http2Stream` is made. 182 183If the `'frameError'` event is associated with a stream, the stream will be 184closed and destroyed immediately following the `'frameError'` event. If the 185event is not associated with a stream, the `Http2Session` will be shut down 186immediately following the `'frameError'` event. 187 188#### Event: 'goaway' 189<!-- YAML 190added: v8.4.0 191--> 192 193* `errorCode` {number} The HTTP/2 error code specified in the `GOAWAY` frame. 194* `lastStreamID` {number} The ID of the last stream the remote peer successfully 195 processed (or `0` if no ID is specified). 196* `opaqueData` {Buffer} If additional opaque data was included in the `GOAWAY` 197 frame, a `Buffer` instance will be passed containing that data. 198 199The `'goaway'` event is emitted when a `GOAWAY` frame is received. 200 201The `Http2Session` instance will be shut down automatically when the `'goaway'` 202event is emitted. 203 204#### Event: 'localSettings' 205<!-- YAML 206added: v8.4.0 207--> 208 209* `settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received. 210 211The `'localSettings'` event is emitted when an acknowledgment `SETTINGS` frame 212has been received. 213 214When using `http2session.settings()` to submit new settings, the modified 215settings do not take effect until the `'localSettings'` event is emitted. 216 217```js 218session.settings({ enablePush: false }); 219 220session.on('localSettings', (settings) => { 221 /* Use the new settings */ 222}); 223``` 224 225#### Event: 'ping' 226<!-- YAML 227added: v10.12.0 228--> 229 230* `payload` {Buffer} The `PING` frame 8-byte payload 231 232The `'ping'` event is emitted whenever a `PING` frame is received from the 233connected peer. 234 235#### Event: 'remoteSettings' 236<!-- YAML 237added: v8.4.0 238--> 239 240* `settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received. 241 242The `'remoteSettings'` event is emitted when a new `SETTINGS` frame is received 243from the connected peer. 244 245```js 246session.on('remoteSettings', (settings) => { 247 /* Use the new settings */ 248}); 249``` 250 251#### Event: 'stream' 252<!-- YAML 253added: v8.4.0 254--> 255 256* `stream` {Http2Stream} A reference to the stream 257* `headers` {HTTP/2 Headers Object} An object describing the headers 258* `flags` {number} The associated numeric flags 259* `rawHeaders` {Array} An array containing the raw header names followed by 260 their respective values. 261 262The `'stream'` event is emitted when a new `Http2Stream` is created. 263 264```js 265const http2 = require('http2'); 266session.on('stream', (stream, headers, flags) => { 267 const method = headers[':method']; 268 const path = headers[':path']; 269 // ... 270 stream.respond({ 271 ':status': 200, 272 'content-type': 'text/plain' 273 }); 274 stream.write('hello '); 275 stream.end('world'); 276}); 277``` 278 279On the server side, user code will typically not listen for this event directly, 280and would instead register a handler for the `'stream'` event emitted by the 281`net.Server` or `tls.Server` instances returned by `http2.createServer()` and 282`http2.createSecureServer()`, respectively, as in the example below: 283 284```js 285const http2 = require('http2'); 286 287// Create an unencrypted HTTP/2 server 288const server = http2.createServer(); 289 290server.on('stream', (stream, headers) => { 291 stream.respond({ 292 'content-type': 'text/html', 293 ':status': 200 294 }); 295 stream.on('error', (error) => console.error(error)); 296 stream.end('<h1>Hello World</h1>'); 297}); 298 299server.listen(80); 300``` 301 302Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence, 303a network error will destroy each individual stream and must be handled on the 304stream level, as shown above. 305 306#### Event: 'timeout' 307<!-- YAML 308added: v8.4.0 309--> 310 311After the `http2session.setTimeout()` method is used to set the timeout period 312for this `Http2Session`, the `'timeout'` event is emitted if there is no 313activity on the `Http2Session` after the configured number of milliseconds. 314 315```js 316session.setTimeout(2000); 317session.on('timeout', () => { /* .. */ }); 318``` 319 320#### http2session.alpnProtocol 321<!-- YAML 322added: v9.4.0 323--> 324 325* {string|undefined} 326 327Value will be `undefined` if the `Http2Session` is not yet connected to a 328socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or 329will return the value of the connected `TLSSocket`'s own `alpnProtocol` 330property. 331 332#### http2session.close([callback]) 333<!-- YAML 334added: v9.4.0 335--> 336 337* `callback` {Function} 338 339Gracefully closes the `Http2Session`, allowing any existing streams to 340complete on their own and preventing new `Http2Stream` instances from being 341created. Once closed, `http2session.destroy()` *might* be called if there 342are no open `Http2Stream` instances. 343 344If specified, the `callback` function is registered as a handler for the 345`'close'` event. 346 347#### http2session.closed 348<!-- YAML 349added: v9.4.0 350--> 351 352* {boolean} 353 354Will be `true` if this `Http2Session` instance has been closed, otherwise 355`false`. 356 357#### http2session.connecting 358<!-- YAML 359added: v10.0.0 360--> 361 362* {boolean} 363 364Will be `true` if this `Http2Session` instance is still connecting, will be set 365to `false` before emitting `connect` event and/or calling the `http2.connect` 366callback. 367 368#### http2session.destroy([error][, code]) 369<!-- YAML 370added: v8.4.0 371--> 372 373* `error` {Error} An `Error` object if the `Http2Session` is being destroyed 374 due to an error. 375* `code` {number} The HTTP/2 error code to send in the final `GOAWAY` frame. 376 If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, 377 otherwise defaults to `NO_ERROR`. 378 379Immediately terminates the `Http2Session` and the associated `net.Socket` or 380`tls.TLSSocket`. 381 382Once destroyed, the `Http2Session` will emit the `'close'` event. If `error` 383is not undefined, an `'error'` event will be emitted immediately before the 384`'close'` event. 385 386If there are any remaining open `Http2Streams` associated with the 387`Http2Session`, those will also be destroyed. 388 389#### http2session.destroyed 390<!-- YAML 391added: v8.4.0 392--> 393 394* {boolean} 395 396Will be `true` if this `Http2Session` instance has been destroyed and must no 397longer be used, otherwise `false`. 398 399#### http2session.encrypted 400<!-- YAML 401added: v9.4.0 402--> 403 404* {boolean|undefined} 405 406Value is `undefined` if the `Http2Session` session socket has not yet been 407connected, `true` if the `Http2Session` is connected with a `TLSSocket`, 408and `false` if the `Http2Session` is connected to any other kind of socket 409or stream. 410 411#### http2session.goaway([code[, lastStreamID[, opaqueData]]]) 412<!-- YAML 413added: v9.4.0 414--> 415 416* `code` {number} An HTTP/2 error code 417* `lastStreamID` {number} The numeric ID of the last processed `Http2Stream` 418* `opaqueData` {Buffer|TypedArray|DataView} A `TypedArray` or `DataView` 419 instance containing additional data to be carried within the `GOAWAY` frame. 420 421Transmits a `GOAWAY` frame to the connected peer *without* shutting down the 422`Http2Session`. 423 424#### http2session.localSettings 425<!-- YAML 426added: v8.4.0 427--> 428 429* {HTTP/2 Settings Object} 430 431A prototype-less object describing the current local settings of this 432`Http2Session`. The local settings are local to *this* `Http2Session` instance. 433 434#### http2session.originSet 435<!-- YAML 436added: v9.4.0 437--> 438 439* {string[]|undefined} 440 441If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property 442will return an `Array` of origins for which the `Http2Session` may be 443considered authoritative. 444 445The `originSet` property is only available when using a secure TLS connection. 446 447#### http2session.pendingSettingsAck 448<!-- YAML 449added: v8.4.0 450--> 451 452* {boolean} 453 454Indicates whether or not the `Http2Session` is currently waiting for an 455acknowledgment for a sent `SETTINGS` frame. Will be `true` after calling the 456`http2session.settings()` method. Will be `false` once all sent SETTINGS 457frames have been acknowledged. 458 459#### http2session.ping([payload, ]callback) 460<!-- YAML 461added: v8.9.3 462--> 463 464* `payload` {Buffer|TypedArray|DataView} Optional ping payload. 465* `callback` {Function} 466* Returns: {boolean} 467 468Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must 469be provided. The method will return `true` if the `PING` was sent, `false` 470otherwise. 471 472The maximum number of outstanding (unacknowledged) pings is determined by the 473`maxOutstandingPings` configuration option. The default maximum is 10. 474 475If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView` 476containing 8 bytes of data that will be transmitted with the `PING` and 477returned with the ping acknowledgment. 478 479The callback will be invoked with three arguments: an error argument that will 480be `null` if the `PING` was successfully acknowledged, a `duration` argument 481that reports the number of milliseconds elapsed since the ping was sent and the 482acknowledgment was received, and a `Buffer` containing the 8-byte `PING` 483payload. 484 485```js 486session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { 487 if (!err) { 488 console.log(`Ping acknowledged in ${duration} milliseconds`); 489 console.log(`With payload '${payload.toString()}'`); 490 } 491}); 492``` 493 494If the `payload` argument is not specified, the default payload will be the 49564-bit timestamp (little endian) marking the start of the `PING` duration. 496 497#### http2session.ref() 498<!-- YAML 499added: v9.4.0 500--> 501 502Calls [`ref()`][`net.Socket.prototype.ref()`] on this `Http2Session` 503instance's underlying [`net.Socket`]. 504 505#### http2session.remoteSettings 506<!-- YAML 507added: v8.4.0 508--> 509 510* {HTTP/2 Settings Object} 511 512A prototype-less object describing the current remote settings of this 513`Http2Session`. The remote settings are set by the *connected* HTTP/2 peer. 514 515#### http2session.setTimeout(msecs, callback) 516<!-- YAML 517added: v8.4.0 518--> 519 520* `msecs` {number} 521* `callback` {Function} 522 523Used to set a callback function that is called when there is no activity on 524the `Http2Session` after `msecs` milliseconds. The given `callback` is 525registered as a listener on the `'timeout'` event. 526 527#### http2session.socket 528<!-- YAML 529added: v8.4.0 530--> 531 532* {net.Socket|tls.TLSSocket} 533 534Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but 535limits available methods to ones safe to use with HTTP/2. 536 537`destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw 538an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See 539[`Http2Session` and Sockets][] for more information. 540 541`setTimeout` method will be called on this `Http2Session`. 542 543All other interactions will be routed directly to the socket. 544 545#### http2session.state 546<!-- YAML 547added: v8.4.0 548--> 549 550Provides miscellaneous information about the current state of the 551`Http2Session`. 552 553* {Object} 554 * `effectiveLocalWindowSize` {number} The current local (receive) 555 flow control window size for the `Http2Session`. 556 * `effectiveRecvDataLength` {number} The current number of bytes 557 that have been received since the last flow control `WINDOW_UPDATE`. 558 * `nextStreamID` {number} The numeric identifier to be used the 559 next time a new `Http2Stream` is created by this `Http2Session`. 560 * `localWindowSize` {number} The number of bytes that the remote peer can 561 send without receiving a `WINDOW_UPDATE`. 562 * `lastProcStreamID` {number} The numeric id of the `Http2Stream` 563 for which a `HEADERS` or `DATA` frame was most recently received. 564 * `remoteWindowSize` {number} The number of bytes that this `Http2Session` 565 may send without receiving a `WINDOW_UPDATE`. 566 * `outboundQueueSize` {number} The number of frames currently within the 567 outbound queue for this `Http2Session`. 568 * `deflateDynamicTableSize` {number} The current size in bytes of the 569 outbound header compression state table. 570 * `inflateDynamicTableSize` {number} The current size in bytes of the 571 inbound header compression state table. 572 573An object describing the current status of this `Http2Session`. 574 575#### http2session.settings(settings) 576<!-- YAML 577added: v8.4.0 578--> 579 580* `settings` {HTTP/2 Settings Object} 581 582Updates the current local settings for this `Http2Session` and sends a new 583`SETTINGS` frame to the connected HTTP/2 peer. 584 585Once called, the `http2session.pendingSettingsAck` property will be `true` 586while the session is waiting for the remote peer to acknowledge the new 587settings. 588 589The new settings will not become effective until the `SETTINGS` acknowledgment 590is received and the `'localSettings'` event is emitted. It is possible to send 591multiple `SETTINGS` frames while acknowledgment is still pending. 592 593#### http2session.type 594<!-- YAML 595added: v8.4.0 596--> 597 598* {number} 599 600The `http2session.type` will be equal to 601`http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a 602server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a 603client. 604 605#### http2session.unref() 606<!-- YAML 607added: v9.4.0 608--> 609 610Calls [`unref()`][`net.Socket.prototype.unref()`] on this `Http2Session` 611instance's underlying [`net.Socket`]. 612 613### Class: ServerHttp2Session 614<!-- YAML 615added: v8.4.0 616--> 617 618#### serverhttp2session.altsvc(alt, originOrStream) 619<!-- YAML 620added: v9.4.0 621--> 622 623* `alt` {string} A description of the alternative service configuration as 624 defined by [RFC 7838][]. 625* `originOrStream` {number|string|URL|Object} Either a URL string specifying 626 the origin (or an `Object` with an `origin` property) or the numeric 627 identifier of an active `Http2Stream` as given by the `http2stream.id` 628 property. 629 630Submits an `ALTSVC` frame (as defined by [RFC 7838][]) to the connected client. 631 632```js 633const http2 = require('http2'); 634 635const server = http2.createServer(); 636server.on('session', (session) => { 637 // Set altsvc for origin https://example.org:80 638 session.altsvc('h2=":8000"', 'https://example.org:80'); 639}); 640 641server.on('stream', (stream) => { 642 // Set altsvc for a specific stream 643 stream.session.altsvc('h2=":8000"', stream.id); 644}); 645``` 646 647Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate 648service is associated with the origin of the given `Http2Stream`. 649 650The `alt` and origin string *must* contain only ASCII bytes and are 651strictly interpreted as a sequence of ASCII bytes. The special value `'clear'` 652may be passed to clear any previously set alternative service for a given 653domain. 654 655When a string is passed for the `originOrStream` argument, it will be parsed as 656a URL and the origin will be derived. For instance, the origin for the 657HTTP URL `'https://example.org/foo/bar'` is the ASCII string 658`'https://example.org'`. An error will be thrown if either the given string 659cannot be parsed as a URL or if a valid origin cannot be derived. 660 661A `URL` object, or any object with an `origin` property, may be passed as 662`originOrStream`, in which case the value of the `origin` property will be 663used. The value of the `origin` property *must* be a properly serialized 664ASCII origin. 665 666#### Specifying alternative services 667 668The format of the `alt` parameter is strictly defined by [RFC 7838][] as an 669ASCII string containing a comma-delimited list of "alternative" protocols 670associated with a specific host and port. 671 672For example, the value `'h2="example.org:81"'` indicates that the HTTP/2 673protocol is available on the host `'example.org'` on TCP/IP port 81. The 674host and port *must* be contained within the quote (`"`) characters. 675 676Multiple alternatives may be specified, for instance: `'h2="example.org:81", 677h2=":82"'`. 678 679The protocol identifier (`'h2'` in the examples) may be any valid 680[ALPN Protocol ID][]. 681 682The syntax of these values is not validated by the Node.js implementation and 683are passed through as provided by the user or received from the peer. 684 685#### serverhttp2session.origin(...origins) 686<!-- YAML 687added: v10.12.0 688--> 689 690* `origins` { string | URL | Object } One or more URL Strings passed as 691 separate arguments. 692 693Submits an `ORIGIN` frame (as defined by [RFC 8336][]) to the connected client 694to advertise the set of origins for which the server is capable of providing 695authoritative responses. 696 697```js 698const http2 = require('http2'); 699const options = getSecureOptionsSomehow(); 700const server = http2.createSecureServer(options); 701server.on('stream', (stream) => { 702 stream.respond(); 703 stream.end('ok'); 704}); 705server.on('session', (session) => { 706 session.origin('https://example.com', 'https://example.org'); 707}); 708``` 709 710When a string is passed as an `origin`, it will be parsed as a URL and the 711origin will be derived. For instance, the origin for the HTTP URL 712`'https://example.org/foo/bar'` is the ASCII string 713`'https://example.org'`. An error will be thrown if either the given string 714cannot be parsed as a URL or if a valid origin cannot be derived. 715 716A `URL` object, or any object with an `origin` property, may be passed as 717an `origin`, in which case the value of the `origin` property will be 718used. The value of the `origin` property *must* be a properly serialized 719ASCII origin. 720 721Alternatively, the `origins` option may be used when creating a new HTTP/2 722server using the `http2.createSecureServer()` method: 723 724```js 725const http2 = require('http2'); 726const options = getSecureOptionsSomehow(); 727options.origins = ['https://example.com', 'https://example.org']; 728const server = http2.createSecureServer(options); 729server.on('stream', (stream) => { 730 stream.respond(); 731 stream.end('ok'); 732}); 733``` 734 735### Class: ClientHttp2Session 736<!-- YAML 737added: v8.4.0 738--> 739 740#### Event: 'altsvc' 741<!-- YAML 742added: v9.4.0 743--> 744 745* `alt` {string} 746* `origin` {string} 747* `streamId` {number} 748 749The `'altsvc'` event is emitted whenever an `ALTSVC` frame is received by 750the client. The event is emitted with the `ALTSVC` value, origin, and stream 751ID. If no `origin` is provided in the `ALTSVC` frame, `origin` will 752be an empty string. 753 754```js 755const http2 = require('http2'); 756const client = http2.connect('https://example.org'); 757 758client.on('altsvc', (alt, origin, streamId) => { 759 console.log(alt); 760 console.log(origin); 761 console.log(streamId); 762}); 763``` 764 765#### Event: 'origin' 766<!-- YAML 767added: v10.12.0 768--> 769 770* `origins` {string[]} 771 772The `'origin'` event is emitted whenever an `ORIGIN` frame is received by 773the client. The event is emitted with an array of `origin` strings. The 774`http2session.originSet` will be updated to include the received 775origins. 776 777```js 778const http2 = require('http2'); 779const client = http2.connect('https://example.org'); 780 781client.on('origin', (origins) => { 782 for (let n = 0; n < origins.length; n++) 783 console.log(origins[n]); 784}); 785``` 786 787The `'origin'` event is only emitted when using a secure TLS connection. 788 789#### clienthttp2session.request(headers[, options]) 790<!-- YAML 791added: v8.4.0 792--> 793 794* `headers` {HTTP/2 Headers Object} 795* `options` {Object} 796 * `endStream` {boolean} `true` if the `Http2Stream` *writable* side should 797 be closed initially, such as when sending a `GET` request that should not 798 expect a payload body. 799 * `exclusive` {boolean} When `true` and `parent` identifies a parent Stream, 800 the created stream is made the sole direct dependency of the parent, with 801 all other existing dependents made a dependent of the newly created stream. 802 **Default:** `false`. 803 * `parent` {number} Specifies the numeric identifier of a stream the newly 804 created stream is dependent on. 805 * `weight` {number} Specifies the relative dependency of a stream in relation 806 to other streams with the same `parent`. The value is a number between `1` 807 and `256` (inclusive). 808 * `waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the 809 `'wantTrailers'` event after the final `DATA` frame has been sent. 810 811* Returns: {ClientHttp2Stream} 812 813For HTTP/2 Client `Http2Session` instances only, the `http2session.request()` 814creates and returns an `Http2Stream` instance that can be used to send an 815HTTP/2 request to the connected server. 816 817This method is only available if `http2session.type` is equal to 818`http2.constants.NGHTTP2_SESSION_CLIENT`. 819 820```js 821const http2 = require('http2'); 822const clientSession = http2.connect('https://localhost:1234'); 823const { 824 HTTP2_HEADER_PATH, 825 HTTP2_HEADER_STATUS 826} = http2.constants; 827 828const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); 829req.on('response', (headers) => { 830 console.log(headers[HTTP2_HEADER_STATUS]); 831 req.on('data', (chunk) => { /* .. */ }); 832 req.on('end', () => { /* .. */ }); 833}); 834``` 835 836When the `options.waitForTrailers` option is set, the `'wantTrailers'` event 837is emitted immediately after queuing the last chunk of payload data to be sent. 838The `http2stream.sendTrailers()` method can then be called to send trailing 839headers to the peer. 840 841When `options.waitForTrailers` is set, the `Http2Stream` will not automatically 842close when the final `DATA` frame is transmitted. User code must call either 843`http2stream.sendTrailers()` or `http2stream.close()` to close the 844`Http2Stream`. 845 846The `:method` and `:path` pseudo-headers are not specified within `headers`, 847they respectively default to: 848 849* `:method` = `'GET'` 850* `:path` = `/` 851 852### Class: Http2Stream 853<!-- YAML 854added: v8.4.0 855--> 856 857* Extends: {stream.Duplex} 858 859Each instance of the `Http2Stream` class represents a bidirectional HTTP/2 860communications stream over an `Http2Session` instance. Any single `Http2Session` 861may have up to 2<sup>31</sup>-1 `Http2Stream` instances over its lifetime. 862 863User code will not construct `Http2Stream` instances directly. Rather, these 864are created, managed, and provided to user code through the `Http2Session` 865instance. On the server, `Http2Stream` instances are created either in response 866to an incoming HTTP request (and handed off to user code via the `'stream'` 867event), or in response to a call to the `http2stream.pushStream()` method. 868On the client, `Http2Stream` instances are created and returned when either the 869`http2session.request()` method is called, or in response to an incoming 870`'push'` event. 871 872The `Http2Stream` class is a base for the [`ServerHttp2Stream`][] and 873[`ClientHttp2Stream`][] classes, each of which is used specifically by either 874the Server or Client side, respectively. 875 876All `Http2Stream` instances are [`Duplex`][] streams. The `Writable` side of the 877`Duplex` is used to send data to the connected peer, while the `Readable` side 878is used to receive data sent by the connected peer. 879 880#### Http2Stream Lifecycle 881 882##### Creation 883 884On the server side, instances of [`ServerHttp2Stream`][] are created either 885when: 886 887* A new HTTP/2 `HEADERS` frame with a previously unused stream ID is received; 888* The `http2stream.pushStream()` method is called. 889 890On the client side, instances of [`ClientHttp2Stream`][] are created when the 891`http2session.request()` method is called. 892 893On the client, the `Http2Stream` instance returned by `http2session.request()` 894may not be immediately ready for use if the parent `Http2Session` has not yet 895been fully established. In such cases, operations called on the `Http2Stream` 896will be buffered until the `'ready'` event is emitted. User code should rarely, 897if ever, need to handle the `'ready'` event directly. The ready status of an 898`Http2Stream` can be determined by checking the value of `http2stream.id`. If 899the value is `undefined`, the stream is not yet ready for use. 900 901##### Destruction 902 903All [`Http2Stream`][] instances are destroyed either when: 904 905* An `RST_STREAM` frame for the stream is received by the connected peer, 906 and (for client streams only) pending data has been read. 907* The `http2stream.close()` method is called, and (for client streams only) 908 pending data has been read. 909* The `http2stream.destroy()` or `http2session.destroy()` methods are called. 910 911When an `Http2Stream` instance is destroyed, an attempt will be made to send an 912`RST_STREAM` frame will be sent to the connected peer. 913 914When the `Http2Stream` instance is destroyed, the `'close'` event will 915be emitted. Because `Http2Stream` is an instance of `stream.Duplex`, the 916`'end'` event will also be emitted if the stream data is currently flowing. 917The `'error'` event may also be emitted if `http2stream.destroy()` was called 918with an `Error` passed as the first argument. 919 920After the `Http2Stream` has been destroyed, the `http2stream.destroyed` 921property will be `true` and the `http2stream.rstCode` property will specify the 922`RST_STREAM` error code. The `Http2Stream` instance is no longer usable once 923destroyed. 924 925#### Event: 'aborted' 926<!-- YAML 927added: v8.4.0 928--> 929 930The `'aborted'` event is emitted whenever a `Http2Stream` instance is 931abnormally aborted in mid-communication. 932 933The `'aborted'` event will only be emitted if the `Http2Stream` writable side 934has not been ended. 935 936#### Event: 'close' 937<!-- YAML 938added: v8.4.0 939--> 940 941The `'close'` event is emitted when the `Http2Stream` is destroyed. Once 942this event is emitted, the `Http2Stream` instance is no longer usable. 943 944The HTTP/2 error code used when closing the stream can be retrieved using 945the `http2stream.rstCode` property. If the code is any value other than 946`NGHTTP2_NO_ERROR` (`0`), an `'error'` event will have also been emitted. 947 948#### Event: 'error' 949<!-- YAML 950added: v8.4.0 951--> 952 953* `error` {Error} 954 955The `'error'` event is emitted when an error occurs during the processing of 956an `Http2Stream`. 957 958#### Event: 'frameError' 959<!-- YAML 960added: v8.4.0 961--> 962 963The `'frameError'` event is emitted when an error occurs while attempting to 964send a frame. When invoked, the handler function will receive an integer 965argument identifying the frame type, and an integer argument identifying the 966error code. The `Http2Stream` instance will be destroyed immediately after the 967`'frameError'` event is emitted. 968 969#### Event: 'timeout' 970<!-- YAML 971added: v8.4.0 972--> 973 974The `'timeout'` event is emitted after no activity is received for this 975`Http2Stream` within the number of milliseconds set using 976`http2stream.setTimeout()`. 977 978#### Event: 'trailers' 979<!-- YAML 980added: v8.4.0 981--> 982 983The `'trailers'` event is emitted when a block of headers associated with 984trailing header fields is received. The listener callback is passed the 985[HTTP/2 Headers Object][] and flags associated with the headers. 986 987Note that this event might not be emitted if `http2stream.end()` is called 988before trailers are received and the incoming data is not being read or 989listened for. 990 991```js 992stream.on('trailers', (headers, flags) => { 993 console.log(headers); 994}); 995``` 996 997#### Event: 'wantTrailers' 998<!-- YAML 999added: v10.0.0 1000--> 1001 1002The `'wantTrailers'` event is emitted when the `Http2Stream` has queued the 1003final `DATA` frame to be sent on a frame and the `Http2Stream` is ready to send 1004trailing headers. When initiating a request or response, the `waitForTrailers` 1005option must be set for this event to be emitted. 1006 1007#### http2stream.aborted 1008<!-- YAML 1009added: v8.4.0 1010--> 1011 1012* {boolean} 1013 1014Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, 1015the `'aborted'` event will have been emitted. 1016 1017#### http2stream.bufferSize 1018<!-- YAML 1019added: v10.16.0 1020--> 1021* {number} 1022 1023This property shows the number of characters currently buffered to be written. 1024See [`net.Socket.bufferSize`][] for details. 1025 1026#### http2stream.close(code[, callback]) 1027<!-- YAML 1028added: v8.4.0 1029--> 1030 1031* `code` {number} Unsigned 32-bit integer identifying the error code. 1032 **Default:** `http2.constants.NGHTTP2_NO_ERROR` (`0x00`). 1033* `callback` {Function} An optional function registered to listen for the 1034 `'close'` event. 1035 1036Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the 1037connected HTTP/2 peer. 1038 1039#### http2stream.closed 1040<!-- YAML 1041added: v9.4.0 1042--> 1043 1044* {boolean} 1045 1046Set to `true` if the `Http2Stream` instance has been closed. 1047 1048#### http2stream.destroyed 1049<!-- YAML 1050added: v8.4.0 1051--> 1052 1053* {boolean} 1054 1055Set to `true` if the `Http2Stream` instance has been destroyed and is no longer 1056usable. 1057 1058#### http2stream.endAfterHeaders 1059<!-- YAML 1060added: v10.11.0 1061--> 1062 1063* {boolean} 1064 1065Set the `true` if the `END_STREAM` flag was set in the request or response 1066HEADERS frame received, indicating that no additional data should be received 1067and the readable side of the `Http2Stream` will be closed. 1068 1069#### http2stream.pending 1070<!-- YAML 1071added: v9.4.0 1072--> 1073 1074* {boolean} 1075 1076Set to `true` if the `Http2Stream` instance has not yet been assigned a 1077numeric stream identifier. 1078 1079#### http2stream.priority(options) 1080<!-- YAML 1081added: v8.4.0 1082--> 1083 1084* `options` {Object} 1085 * `exclusive` {boolean} When `true` and `parent` identifies a parent Stream, 1086 this stream is made the sole direct dependency of the parent, with 1087 all other existing dependents made a dependent of this stream. **Default:** 1088 `false`. 1089 * `parent` {number} Specifies the numeric identifier of a stream this stream 1090 is dependent on. 1091 * `weight` {number} Specifies the relative dependency of a stream in relation 1092 to other streams with the same `parent`. The value is a number between `1` 1093 and `256` (inclusive). 1094 * `silent` {boolean} When `true`, changes the priority locally without 1095 sending a `PRIORITY` frame to the connected peer. 1096 1097Updates the priority for this `Http2Stream` instance. 1098 1099#### http2stream.rstCode 1100<!-- YAML 1101added: v8.4.0 1102--> 1103 1104* {number} 1105 1106Set to the `RST_STREAM` [error code][] reported when the `Http2Stream` is 1107destroyed after either receiving an `RST_STREAM` frame from the connected peer, 1108calling `http2stream.close()`, or `http2stream.destroy()`. Will be 1109`undefined` if the `Http2Stream` has not been closed. 1110 1111#### http2stream.sentHeaders 1112<!-- YAML 1113added: v9.5.0 1114--> 1115 1116* {HTTP/2 Headers Object} 1117 1118An object containing the outbound headers sent for this `Http2Stream`. 1119 1120#### http2stream.sentInfoHeaders 1121<!-- YAML 1122added: v9.5.0 1123--> 1124 1125* {HTTP/2 Headers Object[]} 1126 1127An array of objects containing the outbound informational (additional) headers 1128sent for this `Http2Stream`. 1129 1130#### http2stream.sentTrailers 1131<!-- YAML 1132added: v9.5.0 1133--> 1134 1135* {HTTP/2 Headers Object} 1136 1137An object containing the outbound trailers sent for this `HttpStream`. 1138 1139#### http2stream.session 1140<!-- YAML 1141added: v8.4.0 1142--> 1143 1144* {Http2Session} 1145 1146A reference to the `Http2Session` instance that owns this `Http2Stream`. The 1147value will be `undefined` after the `Http2Stream` instance is destroyed. 1148 1149#### http2stream.setTimeout(msecs, callback) 1150<!-- YAML 1151added: v8.4.0 1152--> 1153 1154* `msecs` {number} 1155* `callback` {Function} 1156 1157```js 1158const http2 = require('http2'); 1159const client = http2.connect('http://example.org:8000'); 1160const { NGHTTP2_CANCEL } = http2.constants; 1161const req = client.request({ ':path': '/' }); 1162 1163// Cancel the stream if there's no activity after 5 seconds 1164req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); 1165``` 1166 1167#### http2stream.state 1168<!-- YAML 1169added: v8.4.0 1170--> 1171Provides miscellaneous information about the current state of the 1172`Http2Stream`. 1173 1174* {Object} 1175 * `localWindowSize` {number} The number of bytes the connected peer may send 1176 for this `Http2Stream` without receiving a `WINDOW_UPDATE`. 1177 * `state` {number} A flag indicating the low-level current state of the 1178 `Http2Stream` as determined by `nghttp2`. 1179 * `localClose` {number} `true` if this `Http2Stream` has been closed locally. 1180 * `remoteClose` {number} `true` if this `Http2Stream` has been closed 1181 remotely. 1182 * `sumDependencyWeight` {number} The sum weight of all `Http2Stream` 1183 instances that depend on this `Http2Stream` as specified using 1184 `PRIORITY` frames. 1185 * `weight` {number} The priority weight of this `Http2Stream`. 1186 1187A current state of this `Http2Stream`. 1188 1189#### http2stream.sendTrailers(headers) 1190<!-- YAML 1191added: v10.0.0 1192--> 1193 1194* `headers` {HTTP/2 Headers Object} 1195 1196Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method 1197will cause the `Http2Stream` to be immediately closed and must only be 1198called after the `'wantTrailers'` event has been emitted. When sending a 1199request or sending a response, the `options.waitForTrailers` option must be set 1200in order to keep the `Http2Stream` open after the final `DATA` frame so that 1201trailers can be sent. 1202 1203```js 1204const http2 = require('http2'); 1205const server = http2.createServer(); 1206server.on('stream', (stream) => { 1207 stream.respond(undefined, { waitForTrailers: true }); 1208 stream.on('wantTrailers', () => { 1209 stream.sendTrailers({ xyz: 'abc' }); 1210 }); 1211 stream.end('Hello World'); 1212}); 1213``` 1214 1215The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header 1216fields (e.g. `':method'`, `':path'`, etc). 1217 1218### Class: ClientHttp2Stream 1219<!-- YAML 1220added: v8.4.0 1221--> 1222 1223* Extends {Http2Stream} 1224 1225The `ClientHttp2Stream` class is an extension of `Http2Stream` that is 1226used exclusively on HTTP/2 Clients. `Http2Stream` instances on the client 1227provide events such as `'response'` and `'push'` that are only relevant on 1228the client. 1229 1230#### Event: 'continue' 1231<!-- YAML 1232added: v8.5.0 1233--> 1234 1235Emitted when the server sends a `100 Continue` status, usually because 1236the request contained `Expect: 100-continue`. This is an instruction that 1237the client should send the request body. 1238 1239#### Event: 'headers' 1240<!-- YAML 1241added: v8.4.0 1242--> 1243 1244The `'headers'` event is emitted when an additional block of headers is received 1245for a stream, such as when a block of `1xx` informational headers is received. 1246The listener callback is passed the [HTTP/2 Headers Object][] and flags 1247associated with the headers. 1248 1249```js 1250stream.on('headers', (headers, flags) => { 1251 console.log(headers); 1252}); 1253``` 1254 1255#### Event: 'push' 1256<!-- YAML 1257added: v8.4.0 1258--> 1259 1260The `'push'` event is emitted when response headers for a Server Push stream 1261are received. The listener callback is passed the [HTTP/2 Headers Object][] and 1262flags associated with the headers. 1263 1264```js 1265stream.on('push', (headers, flags) => { 1266 console.log(headers); 1267}); 1268``` 1269 1270#### Event: 'response' 1271<!-- YAML 1272added: v8.4.0 1273--> 1274 1275The `'response'` event is emitted when a response `HEADERS` frame has been 1276received for this stream from the connected HTTP/2 server. The listener is 1277invoked with two arguments: an `Object` containing the received 1278[HTTP/2 Headers Object][], and flags associated with the headers. 1279 1280```js 1281const http2 = require('http2'); 1282const client = http2.connect('https://localhost'); 1283const req = client.request({ ':path': '/' }); 1284req.on('response', (headers, flags) => { 1285 console.log(headers[':status']); 1286}); 1287``` 1288 1289### Class: ServerHttp2Stream 1290<!-- YAML 1291added: v8.4.0 1292--> 1293 1294* Extends: {Http2Stream} 1295 1296The `ServerHttp2Stream` class is an extension of [`Http2Stream`][] that is 1297used exclusively on HTTP/2 Servers. `Http2Stream` instances on the server 1298provide additional methods such as `http2stream.pushStream()` and 1299`http2stream.respond()` that are only relevant on the server. 1300 1301#### http2stream.additionalHeaders(headers) 1302<!-- YAML 1303added: v8.4.0 1304--> 1305 1306* `headers` {HTTP/2 Headers Object} 1307 1308Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. 1309 1310#### http2stream.headersSent 1311<!-- YAML 1312added: v8.4.0 1313--> 1314 1315* {boolean} 1316 1317True if headers were sent, false otherwise (read-only). 1318 1319#### http2stream.pushAllowed 1320<!-- YAML 1321added: v8.4.0 1322--> 1323 1324* {boolean} 1325 1326Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote 1327client's most recent `SETTINGS` frame. Will be `true` if the remote peer 1328accepts push streams, `false` otherwise. Settings are the same for every 1329`Http2Stream` in the same `Http2Session`. 1330 1331#### http2stream.pushStream(headers[, options], callback) 1332<!-- YAML 1333added: v8.4.0 1334--> 1335 1336* `headers` {HTTP/2 Headers Object} 1337* `options` {Object} 1338 * `exclusive` {boolean} When `true` and `parent` identifies a parent Stream, 1339 the created stream is made the sole direct dependency of the parent, with 1340 all other existing dependents made a dependent of the newly created stream. 1341 **Default:** `false`. 1342 * `parent` {number} Specifies the numeric identifier of a stream the newly 1343 created stream is dependent on. 1344* `callback` {Function} Callback that is called once the push stream has been 1345 initiated. 1346 * `err` {Error} 1347 * `pushStream` {ServerHttp2Stream} The returned `pushStream` object. 1348 * `headers` {HTTP/2 Headers Object} Headers object the `pushStream` was 1349 initiated with. 1350 1351Initiates a push stream. The callback is invoked with the new `Http2Stream` 1352instance created for the push stream passed as the second argument, or an 1353`Error` passed as the first argument. 1354 1355```js 1356const http2 = require('http2'); 1357const server = http2.createServer(); 1358server.on('stream', (stream) => { 1359 stream.respond({ ':status': 200 }); 1360 stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { 1361 if (err) throw err; 1362 pushStream.respond({ ':status': 200 }); 1363 pushStream.end('some pushed data'); 1364 }); 1365 stream.end('some data'); 1366}); 1367``` 1368 1369Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass 1370a `weight` value to `http2stream.priority` with the `silent` option set to 1371`true` to enable server-side bandwidth balancing between concurrent streams. 1372 1373Calling `http2stream.pushStream()` from within a pushed stream is not permitted 1374and will throw an error. 1375 1376#### http2stream.respond([headers[, options]]) 1377<!-- YAML 1378added: v8.4.0 1379--> 1380 1381* `headers` {HTTP/2 Headers Object} 1382* `options` {Object} 1383 * `endStream` {boolean} Set to `true` to indicate that the response will not 1384 include payload data. 1385 * `waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the 1386 `'wantTrailers'` event after the final `DATA` frame has been sent. 1387 1388```js 1389const http2 = require('http2'); 1390const server = http2.createServer(); 1391server.on('stream', (stream) => { 1392 stream.respond({ ':status': 200 }); 1393 stream.end('some data'); 1394}); 1395``` 1396 1397When the `options.waitForTrailers` option is set, the `'wantTrailers'` event 1398will be emitted immediately after queuing the last chunk of payload data to be 1399sent. The `http2stream.sendTrailers()` method can then be used to sent trailing 1400header fields to the peer. 1401 1402When `options.waitForTrailers` is set, the `Http2Stream` will not automatically 1403close when the final `DATA` frame is transmitted. User code must call either 1404`http2stream.sendTrailers()` or `http2stream.close()` to close the 1405`Http2Stream`. 1406 1407```js 1408const http2 = require('http2'); 1409const server = http2.createServer(); 1410server.on('stream', (stream) => { 1411 stream.respond({ ':status': 200 }, { waitForTrailers: true }); 1412 stream.on('wantTrailers', () => { 1413 stream.sendTrailers({ ABC: 'some value to send' }); 1414 }); 1415 stream.end('some data'); 1416}); 1417``` 1418 1419#### http2stream.respondWithFD(fd[, headers[, options]]) 1420<!-- YAML 1421added: v8.4.0 1422changes: 1423 - version: v10.0.0 1424 pr-url: https://github.com/nodejs/node/pull/18936 1425 description: Any readable file descriptor, not necessarily for a 1426 regular file, is supported now. 1427--> 1428 1429* `fd` {number} A readable file descriptor. 1430* `headers` {HTTP/2 Headers Object} 1431* `options` {Object} 1432 * `statCheck` {Function} 1433 * `waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the 1434 `'wantTrailers'` event after the final `DATA` frame has been sent. 1435 * `offset` {number} The offset position at which to begin reading. 1436 * `length` {number} The amount of data from the fd to send. 1437 1438Initiates a response whose data is read from the given file descriptor. No 1439validation is performed on the given file descriptor. If an error occurs while 1440attempting to read data using the file descriptor, the `Http2Stream` will be 1441closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. 1442 1443When used, the `Http2Stream` object's `Duplex` interface will be closed 1444automatically. 1445 1446```js 1447const http2 = require('http2'); 1448const fs = require('fs'); 1449 1450const server = http2.createServer(); 1451server.on('stream', (stream) => { 1452 const fd = fs.openSync('/some/file', 'r'); 1453 1454 const stat = fs.fstatSync(fd); 1455 const headers = { 1456 'content-length': stat.size, 1457 'last-modified': stat.mtime.toUTCString(), 1458 'content-type': 'text/plain' 1459 }; 1460 stream.respondWithFD(fd, headers); 1461 stream.on('close', () => fs.closeSync(fd)); 1462}); 1463``` 1464 1465The optional `options.statCheck` function may be specified to give user code 1466an opportunity to set additional content headers based on the `fs.Stat` details 1467of the given fd. If the `statCheck` function is provided, the 1468`http2stream.respondWithFD()` method will perform an `fs.fstat()` call to 1469collect details on the provided file descriptor. 1470 1471The `offset` and `length` options may be used to limit the response to a 1472specific range subset. This can be used, for instance, to support HTTP Range 1473requests. 1474 1475The file descriptor is not closed when the stream is closed, so it will need 1476to be closed manually once it is no longer needed. 1477Note that using the same file descriptor concurrently for multiple streams 1478is not supported and may result in data loss. Re-using a file descriptor 1479after a stream has finished is supported. 1480 1481When the `options.waitForTrailers` option is set, the `'wantTrailers'` event 1482will be emitted immediately after queuing the last chunk of payload data to be 1483sent. The `http2stream.sendTrailers()` method can then be used to sent trailing 1484header fields to the peer. 1485 1486When `options.waitForTrailers` is set, the `Http2Stream` will not automatically 1487close when the final `DATA` frame is transmitted. User code *must* call either 1488`http2stream.sendTrailers()` or `http2stream.close()` to close the 1489`Http2Stream`. 1490 1491```js 1492const http2 = require('http2'); 1493const fs = require('fs'); 1494 1495const server = http2.createServer(); 1496server.on('stream', (stream) => { 1497 const fd = fs.openSync('/some/file', 'r'); 1498 1499 const stat = fs.fstatSync(fd); 1500 const headers = { 1501 'content-length': stat.size, 1502 'last-modified': stat.mtime.toUTCString(), 1503 'content-type': 'text/plain' 1504 }; 1505 stream.respondWithFD(fd, headers, { waitForTrailers: true }); 1506 stream.on('wantTrailers', () => { 1507 stream.sendTrailers({ ABC: 'some value to send' }); 1508 }); 1509 1510 stream.on('close', () => fs.closeSync(fd)); 1511}); 1512``` 1513 1514#### http2stream.respondWithFile(path[, headers[, options]]) 1515<!-- YAML 1516added: v8.4.0 1517changes: 1518 - version: v10.0.0 1519 pr-url: https://github.com/nodejs/node/pull/18936 1520 description: Any readable file, not necessarily a 1521 regular file, is supported now. 1522--> 1523 1524* `path` {string|Buffer|URL} 1525* `headers` {HTTP/2 Headers Object} 1526* `options` {Object} 1527 * `statCheck` {Function} 1528 * `onError` {Function} Callback function invoked in the case of an 1529 error before send. 1530 * `waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the 1531 `'wantTrailers'` event after the final `DATA` frame has been sent. 1532 * `offset` {number} The offset position at which to begin reading. 1533 * `length` {number} The amount of data from the fd to send. 1534 1535Sends a regular file as the response. The `path` must specify a regular file 1536or an `'error'` event will be emitted on the `Http2Stream` object. 1537 1538When used, the `Http2Stream` object's `Duplex` interface will be closed 1539automatically. 1540 1541The optional `options.statCheck` function may be specified to give user code 1542an opportunity to set additional content headers based on the `fs.Stat` details 1543of the given file: 1544 1545If an error occurs while attempting to read the file data, the `Http2Stream` 1546will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` 1547code. If the `onError` callback is defined, then it will be called. Otherwise 1548the stream will be destroyed. 1549 1550Example using a file path: 1551 1552```js 1553const http2 = require('http2'); 1554const server = http2.createServer(); 1555server.on('stream', (stream) => { 1556 function statCheck(stat, headers) { 1557 headers['last-modified'] = stat.mtime.toUTCString(); 1558 } 1559 1560 function onError(err) { 1561 if (err.code === 'ENOENT') { 1562 stream.respond({ ':status': 404 }); 1563 } else { 1564 stream.respond({ ':status': 500 }); 1565 } 1566 stream.end(); 1567 } 1568 1569 stream.respondWithFile('/some/file', 1570 { 'content-type': 'text/plain' }, 1571 { statCheck, onError }); 1572}); 1573``` 1574 1575The `options.statCheck` function may also be used to cancel the send operation 1576by returning `false`. For instance, a conditional request may check the stat 1577results to determine if the file has been modified to return an appropriate 1578`304` response: 1579 1580```js 1581const http2 = require('http2'); 1582const server = http2.createServer(); 1583server.on('stream', (stream) => { 1584 function statCheck(stat, headers) { 1585 // Check the stat here... 1586 stream.respond({ ':status': 304 }); 1587 return false; // Cancel the send operation 1588 } 1589 stream.respondWithFile('/some/file', 1590 { 'content-type': 'text/plain' }, 1591 { statCheck }); 1592}); 1593``` 1594 1595The `content-length` header field will be automatically set. 1596 1597The `offset` and `length` options may be used to limit the response to a 1598specific range subset. This can be used, for instance, to support HTTP Range 1599requests. 1600 1601The `options.onError` function may also be used to handle all the errors 1602that could happen before the delivery of the file is initiated. The 1603default behavior is to destroy the stream. 1604 1605When the `options.waitForTrailers` option is set, the `'wantTrailers'` event 1606will be emitted immediately after queuing the last chunk of payload data to be 1607sent. The `http2stream.sendTrailers()` method can then be used to sent trailing 1608header fields to the peer. 1609 1610When `options.waitForTrailers` is set, the `Http2Stream` will not automatically 1611close when the final `DATA` frame is transmitted. User code must call either 1612`http2stream.sendTrailers()` or `http2stream.close()` to close the 1613`Http2Stream`. 1614 1615```js 1616const http2 = require('http2'); 1617const server = http2.createServer(); 1618server.on('stream', (stream) => { 1619 stream.respondWithFile('/some/file', 1620 { 'content-type': 'text/plain' }, 1621 { waitForTrailers: true }); 1622 stream.on('wantTrailers', () => { 1623 stream.sendTrailers({ ABC: 'some value to send' }); 1624 }); 1625}); 1626``` 1627 1628### Class: Http2Server 1629<!-- YAML 1630added: v8.4.0 1631--> 1632 1633* Extends: {net.Server} 1634 1635Instances of `Http2Server` are created using the `http2.createServer()` 1636function. The `Http2Server` class is not exported directly by the `http2` 1637module. 1638 1639#### Event: 'checkContinue' 1640<!-- YAML 1641added: v8.5.0 1642--> 1643 1644* `request` {http2.Http2ServerRequest} 1645* `response` {http2.Http2ServerResponse} 1646 1647If a [`'request'`][] listener is registered or [`http2.createServer()`][] is 1648supplied a callback function, the `'checkContinue'` event is emitted each time 1649a request with an HTTP `Expect: 100-continue` is received. If this event is 1650not listened for, the server will automatically respond with a status 1651`100 Continue` as appropriate. 1652 1653Handling this event involves calling [`response.writeContinue()`][] if the 1654client should continue to send the request body, or generating an appropriate 1655HTTP response (e.g. 400 Bad Request) if the client should not continue to send 1656the request body. 1657 1658Note that when this event is emitted and handled, the [`'request'`][] event will 1659not be emitted. 1660 1661#### Event: 'request' 1662<!-- YAML 1663added: v8.4.0 1664--> 1665 1666* `request` {http2.Http2ServerRequest} 1667* `response` {http2.Http2ServerResponse} 1668 1669Emitted each time there is a request. Note that there may be multiple requests 1670per session. See the [Compatibility API][]. 1671 1672#### Event: 'session' 1673<!-- YAML 1674added: v8.4.0 1675--> 1676 1677The `'session'` event is emitted when a new `Http2Session` is created by the 1678`Http2Server`. 1679 1680#### Event: 'sessionError' 1681<!-- YAML 1682added: v8.4.0 1683--> 1684 1685The `'sessionError'` event is emitted when an `'error'` event is emitted by 1686an `Http2Session` object associated with the `Http2Server`. 1687 1688#### Event: 'stream' 1689<!-- YAML 1690added: v8.4.0 1691--> 1692 1693The `'stream'` event is emitted when a `'stream'` event has been emitted by 1694an `Http2Session` associated with the server. 1695 1696```js 1697const http2 = require('http2'); 1698const { 1699 HTTP2_HEADER_METHOD, 1700 HTTP2_HEADER_PATH, 1701 HTTP2_HEADER_STATUS, 1702 HTTP2_HEADER_CONTENT_TYPE 1703} = http2.constants; 1704 1705const server = http2.createServer(); 1706server.on('stream', (stream, headers, flags) => { 1707 const method = headers[HTTP2_HEADER_METHOD]; 1708 const path = headers[HTTP2_HEADER_PATH]; 1709 // ... 1710 stream.respond({ 1711 [HTTP2_HEADER_STATUS]: 200, 1712 [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain' 1713 }); 1714 stream.write('hello '); 1715 stream.end('world'); 1716}); 1717``` 1718 1719#### Event: 'timeout' 1720<!-- YAML 1721added: v8.4.0 1722--> 1723 1724The `'timeout'` event is emitted when there is no activity on the Server for 1725a given number of milliseconds set using `http2server.setTimeout()`. 1726**Default:** 2 minutes. 1727 1728#### server.close([callback]) 1729<!-- YAML 1730added: v8.4.0 1731--> 1732* `callback` {Function} 1733 1734Stops the server from accepting new connections. See [`net.Server.close()`][]. 1735 1736Note that this is not analogous to restricting new requests since HTTP/2 1737connections are persistent. To achieve a similar graceful shutdown behavior, 1738consider also using [`http2session.close()`] on active sessions. 1739 1740#### server.setTimeout([msecs][, callback]) 1741<!-- YAML 1742added: v8.4.0 1743--> 1744 1745* `msecs` {number} **Default:** `120000` (2 minutes) 1746* `callback` {Function} 1747* Returns: {Http2Server} 1748 1749Used to set the timeout value for http2 server requests, 1750and sets a callback function that is called when there is no activity 1751on the `Http2Server` after `msecs` milliseconds. 1752 1753The given callback is registered as a listener on the `'timeout'` event. 1754 1755In case of no callback function were assigned, a new `ERR_INVALID_CALLBACK` 1756error will be thrown. 1757 1758### Class: Http2SecureServer 1759<!-- YAML 1760added: v8.4.0 1761--> 1762 1763* Extends: {tls.Server} 1764 1765Instances of `Http2SecureServer` are created using the 1766`http2.createSecureServer()` function. The `Http2SecureServer` class is not 1767exported directly by the `http2` module. 1768 1769#### Event: 'checkContinue' 1770<!-- YAML 1771added: v8.5.0 1772--> 1773 1774* `request` {http2.Http2ServerRequest} 1775* `response` {http2.Http2ServerResponse} 1776 1777If a [`'request'`][] listener is registered or [`http2.createSecureServer()`][] 1778is supplied a callback function, the `'checkContinue'` event is emitted each 1779time a request with an HTTP `Expect: 100-continue` is received. If this event 1780is not listened for, the server will automatically respond with a status 1781`100 Continue` as appropriate. 1782 1783Handling this event involves calling [`response.writeContinue()`][] if the 1784client should continue to send the request body, or generating an appropriate 1785HTTP response (e.g. 400 Bad Request) if the client should not continue to send 1786the request body. 1787 1788Note that when this event is emitted and handled, the [`'request'`][] event will 1789not be emitted. 1790 1791#### Event: 'request' 1792<!-- YAML 1793added: v8.4.0 1794--> 1795 1796* `request` {http2.Http2ServerRequest} 1797* `response` {http2.Http2ServerResponse} 1798 1799Emitted each time there is a request. Note that there may be multiple requests 1800per session. See the [Compatibility API][]. 1801 1802#### Event: 'session' 1803<!-- YAML 1804added: v8.4.0 1805--> 1806 1807The `'session'` event is emitted when a new `Http2Session` is created by the 1808`Http2SecureServer`. 1809 1810#### Event: 'sessionError' 1811<!-- YAML 1812added: v8.4.0 1813--> 1814 1815The `'sessionError'` event is emitted when an `'error'` event is emitted by 1816an `Http2Session` object associated with the `Http2SecureServer`. 1817 1818#### Event: 'stream' 1819<!-- YAML 1820added: v8.4.0 1821--> 1822 1823The `'stream'` event is emitted when a `'stream'` event has been emitted by 1824an `Http2Session` associated with the server. 1825 1826```js 1827const http2 = require('http2'); 1828const { 1829 HTTP2_HEADER_METHOD, 1830 HTTP2_HEADER_PATH, 1831 HTTP2_HEADER_STATUS, 1832 HTTP2_HEADER_CONTENT_TYPE 1833} = http2.constants; 1834 1835const options = getOptionsSomehow(); 1836 1837const server = http2.createSecureServer(options); 1838server.on('stream', (stream, headers, flags) => { 1839 const method = headers[HTTP2_HEADER_METHOD]; 1840 const path = headers[HTTP2_HEADER_PATH]; 1841 // ... 1842 stream.respond({ 1843 [HTTP2_HEADER_STATUS]: 200, 1844 [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain' 1845 }); 1846 stream.write('hello '); 1847 stream.end('world'); 1848}); 1849``` 1850 1851#### Event: 'timeout' 1852<!-- YAML 1853added: v8.4.0 1854--> 1855 1856The `'timeout'` event is emitted when there is no activity on the Server for 1857a given number of milliseconds set using `http2secureServer.setTimeout()`. 1858**Default:** 2 minutes. 1859 1860#### Event: 'unknownProtocol' 1861<!-- YAML 1862added: v8.4.0 1863--> 1864 1865The `'unknownProtocol'` event is emitted when a connecting client fails to 1866negotiate an allowed protocol (i.e. HTTP/2 or HTTP/1.1). The event handler 1867receives the socket for handling. If no listener is registered for this event, 1868the connection is terminated. A timeout may be specified using the 1869`'unknownProtocolTimeout'` option passed to [`http2.createSecureServer()`][]. 1870See the [Compatibility API][]. 1871 1872#### server.close([callback]) 1873<!-- YAML 1874added: v8.4.0 1875--> 1876* `callback` {Function} 1877 1878Stops the server from accepting new connections. See [`tls.Server.close()`][]. 1879 1880Note that this is not analogous to restricting new requests since HTTP/2 1881connections are persistent. To achieve a similar graceful shutdown behavior, 1882consider also using [`http2session.close()`] on active sessions. 1883 1884#### server.setTimeout([msecs][, callback]) 1885<!-- YAML 1886added: v8.4.0 1887--> 1888 1889* `msecs` {number} **Default:** `120000` (2 minutes) 1890* `callback` {Function} 1891* Returns: {Http2SecureServer} 1892 1893Used to set the timeout value for http2 secure server requests, 1894and sets a callback function that is called when there is no activity 1895on the `Http2SecureServer` after `msecs` milliseconds. 1896 1897The given callback is registered as a listener on the `'timeout'` event. 1898 1899In case of no callback function were assigned, a new `ERR_INVALID_CALLBACK` 1900error will be thrown. 1901 1902### http2.createServer(options[, onRequestHandler]) 1903<!-- YAML 1904added: v8.4.0 1905changes: 1906 - version: v10.24.0 1907 pr-url: https://github.com/nodejs-private/node-private/pull/248 1908 description: Added `unknownProtocolTimeout` option with a default of 10000. 1909 - version: v10.21.0 1910 pr-url: https://github.com/nodejs-private/node-private/pull/204 1911 description: Added `maxSettings` option with a default of 32. 1912 - version: v8.9.3 1913 pr-url: https://github.com/nodejs/node/pull/17105 1914 description: Added the `maxOutstandingPings` option with a default limit of 1915 10. 1916 - version: v8.9.3 1917 pr-url: https://github.com/nodejs/node/pull/16676 1918 description: Added the `maxHeaderListPairs` option with a default limit of 1919 128 header pairs. 1920 - version: v9.6.0 1921 pr-url: https://github.com/nodejs/node/pull/15752 1922 description: Added the `Http1IncomingMessage` and `Http1ServerResponse` 1923 option. 1924--> 1925 1926* `options` {Object} 1927 * `maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size 1928 for deflating header fields. **Default:** `4Kib`. 1929 * `maxSettings` {number} Sets the maximum number of settings entries per 1930 `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`. 1931 * `maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` 1932 is permitted to use. The value is expressed in terms of number of megabytes, 1933 e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. 1934 This is a credit based limit, existing `Http2Stream`s may cause this 1935 limit to be exceeded, but new `Http2Stream` instances will be rejected 1936 while this limit is exceeded. The current number of `Http2Stream` sessions, 1937 the current memory use of the header compression tables, current data 1938 queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all 1939 counted towards the current limit. **Default:** `10`. 1940 * `maxHeaderListPairs` {number} Sets the maximum number of header entries. 1941 The minimum value is `4`. **Default:** `128`. 1942 * `maxOutstandingPings` {number} Sets the maximum number of outstanding, 1943 unacknowledged pings. **Default:** `10`. 1944 * `maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a 1945 serialized, compressed block of headers. Attempts to send headers that 1946 exceed this limit will result in a `'frameError'` event being emitted 1947 and the stream being closed and destroyed. 1948 * `paddingStrategy` {number} Identifies the strategy used for determining the 1949 amount of padding to use for `HEADERS` and `DATA` frames. **Default:** 1950 `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of: 1951 * `http2.constants.PADDING_STRATEGY_NONE` - Specifies that no padding is 1952 to be applied. 1953 * `http2.constants.PADDING_STRATEGY_MAX` - Specifies that the maximum 1954 amount of padding, as determined by the internal implementation, is to 1955 be applied. 1956 * `http2.constants.PADDING_STRATEGY_CALLBACK` - Specifies that the user 1957 provided `options.selectPadding()` callback is to be used to determine 1958 the amount of padding. 1959 * `http2.constants.PADDING_STRATEGY_ALIGNED` - Will *attempt* to apply 1960 enough padding to ensure that the total frame length, including the 1961 9-byte header, is a multiple of 8. For each frame, however, there is a 1962 maximum allowed number of padding bytes that is determined by current 1963 flow control state and settings. If this maximum is less than the 1964 calculated amount needed to ensure alignment, the maximum will be used 1965 and the total frame length will *not* necessarily be aligned at 8 bytes. 1966 * `peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent 1967 streams for the remote peer as if a `SETTINGS` frame had been received. Will 1968 be overridden if the remote peer sets its own value for 1969 `maxConcurrentStreams`. **Default:** `100`. 1970 * `selectPadding` {Function} When `options.paddingStrategy` is equal to 1971 `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function 1972 used to determine the padding. See [Using `options.selectPadding()`][]. 1973 * `settings` {HTTP/2 Settings Object} The initial settings to send to the 1974 remote peer upon connection. 1975 * `Http1IncomingMessage` {http.IncomingMessage} Specifies the 1976 `IncomingMessage` class to used for HTTP/1 fallback. Useful for extending 1977 the original `http.IncomingMessage`. **Default:** `http.IncomingMessage`. 1978 * `Http1ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` 1979 class to used for HTTP/1 fallback. Useful for extending the original 1980 `http.ServerResponse`. **Default:** `http.ServerResponse`. 1981 * `Http2ServerRequest` {http2.Http2ServerRequest} Specifies the 1982 `Http2ServerRequest` class to use. 1983 Useful for extending the original `Http2ServerRequest`. 1984 **Default:** `Http2ServerRequest`. 1985 * `Http2ServerResponse` {http2.Http2ServerResponse} Specifies the 1986 `Http2ServerResponse` class to use. 1987 Useful for extending the original `Http2ServerResponse`. 1988 **Default:** `Http2ServerResponse`. 1989 * `unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that 1990 a server should wait when an [`'unknownProtocol'`][] is emitted. If the 1991 socket has not been destroyed by that time the server will destroy it. 1992 **Default:** `10000`. 1993* `onRequestHandler` {Function} See [Compatibility API][] 1994* Returns: {Http2Server} 1995 1996Returns a `net.Server` instance that creates and manages `Http2Session` 1997instances. 1998 1999Since there are no browsers known that support 2000[unencrypted HTTP/2][HTTP/2 Unencrypted], the use of 2001[`http2.createSecureServer()`][] is necessary when communicating 2002with browser clients. 2003 2004```js 2005const http2 = require('http2'); 2006 2007// Create an unencrypted HTTP/2 server. 2008// Since there are no browsers known that support 2009// unencrypted HTTP/2, the use of `http2.createSecureServer()` 2010// is necessary when communicating with browser clients. 2011const server = http2.createServer(); 2012 2013server.on('stream', (stream, headers) => { 2014 stream.respond({ 2015 'content-type': 'text/html', 2016 ':status': 200 2017 }); 2018 stream.end('<h1>Hello World</h1>'); 2019}); 2020 2021server.listen(80); 2022``` 2023 2024### http2.createSecureServer(options[, onRequestHandler]) 2025<!-- YAML 2026added: v8.4.0 2027changes: 2028 - version: v10.24.0 2029 pr-url: https://github.com/nodejs-private/node-private/pull/248 2030 description: Added `unknownProtocolTimeout` option with a default of 10000. 2031 - version: v10.21.0 2032 pr-url: https://github.com/nodejs-private/node-private/pull/204 2033 description: Added `maxSettings` option with a default of 32. 2034 - version: v10.12.0 2035 pr-url: https://github.com/nodejs/node/pull/22956 2036 description: Added the `origins` option to automatically send an `ORIGIN` 2037 frame on `Http2Session` startup. 2038 - version: v8.9.3 2039 pr-url: https://github.com/nodejs/node/pull/17105 2040 description: Added the `maxOutstandingPings` option with a default limit of 2041 10. 2042 - version: v8.9.3 2043 pr-url: https://github.com/nodejs/node/pull/16676 2044 description: Added the `maxHeaderListPairs` option with a default limit of 2045 128 header pairs. 2046--> 2047 2048* `options` {Object} 2049 * `allowHTTP1` {boolean} Incoming client connections that do not support 2050 HTTP/2 will be downgraded to HTTP/1.x when set to `true`. 2051 See the [`'unknownProtocol'`][] event. See [ALPN negotiation][]. 2052 **Default:** `false`. 2053 * `maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size 2054 for deflating header fields. **Default:** `4Kib`. 2055 * `maxSettings` {number} Sets the maximum number of settings entries per 2056 `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`. 2057 * `maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` 2058 is permitted to use. The value is expressed in terms of number of megabytes, 2059 e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a 2060 credit based limit, existing `Http2Stream`s may cause this 2061 limit to be exceeded, but new `Http2Stream` instances will be rejected 2062 while this limit is exceeded. The current number of `Http2Stream` sessions, 2063 the current memory use of the header compression tables, current data 2064 queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all 2065 counted towards the current limit. **Default:** `10`. 2066 * `maxHeaderListPairs` {number} Sets the maximum number of header entries. 2067 The minimum value is `4`. **Default:** `128`. 2068 * `maxOutstandingPings` {number} Sets the maximum number of outstanding, 2069 unacknowledged pings. **Default:** `10`. 2070 * `maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a 2071 serialized, compressed block of headers. Attempts to send headers that 2072 exceed this limit will result in a `'frameError'` event being emitted 2073 and the stream being closed and destroyed. 2074 * `paddingStrategy` {number} Identifies the strategy used for determining the 2075 amount of padding to use for `HEADERS` and `DATA` frames. **Default:** 2076 `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of: 2077 * `http2.constants.PADDING_STRATEGY_NONE` - Specifies that no padding is 2078 to be applied. 2079 * `http2.constants.PADDING_STRATEGY_MAX` - Specifies that the maximum 2080 amount of padding, as determined by the internal implementation, is to 2081 be applied. 2082 * `http2.constants.PADDING_STRATEGY_CALLBACK` - Specifies that the user 2083 provided `options.selectPadding()` callback is to be used to determine 2084 the amount of padding. 2085 * `http2.constants.PADDING_STRATEGY_ALIGNED` - Will *attempt* to apply 2086 enough padding to ensure that the total frame length, including the 2087 9-byte header, is a multiple of 8. For each frame, however, there is a 2088 maximum allowed number of padding bytes that is determined by current 2089 flow control state and settings. If this maximum is less than the 2090 calculated amount needed to ensure alignment, the maximum will be used 2091 and the total frame length will *not* necessarily be aligned at 8 bytes. 2092 * `peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent 2093 streams for the remote peer as if a `SETTINGS` frame had been received. Will 2094 be overridden if the remote peer sets its own value for 2095 `maxConcurrentStreams`. **Default:** `100`. 2096 * `selectPadding` {Function} When `options.paddingStrategy` is equal to 2097 `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function 2098 used to determine the padding. See [Using `options.selectPadding()`][]. 2099 * `settings` {HTTP/2 Settings Object} The initial settings to send to the 2100 remote peer upon connection. 2101 * ...: Any [`tls.createServer()`][] options can be provided. For 2102 servers, the identity options (`pfx` or `key`/`cert`) are usually required. 2103 * `origins` {string[]} An array of origin strings to send within an `ORIGIN` 2104 frame immediately following creation of a new server `Http2Session`. 2105 * `unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that 2106 a server should wait when an [`'unknownProtocol'`][] event is emitted. If 2107 the socket has not been destroyed by that time the server will destroy it. 2108 **Default:** `10000`. 2109* `onRequestHandler` {Function} See [Compatibility API][] 2110* Returns: {Http2SecureServer} 2111 2112Returns a `tls.Server` instance that creates and manages `Http2Session` 2113instances. 2114 2115```js 2116const http2 = require('http2'); 2117const fs = require('fs'); 2118 2119const options = { 2120 key: fs.readFileSync('server-key.pem'), 2121 cert: fs.readFileSync('server-cert.pem') 2122}; 2123 2124// Create a secure HTTP/2 server 2125const server = http2.createSecureServer(options); 2126 2127server.on('stream', (stream, headers) => { 2128 stream.respond({ 2129 'content-type': 'text/html', 2130 ':status': 200 2131 }); 2132 stream.end('<h1>Hello World</h1>'); 2133}); 2134 2135server.listen(80); 2136``` 2137 2138### http2.connect(authority[, options][, listener]) 2139<!-- YAML 2140added: v8.4.0 2141changes: 2142 - version: v10.24.0 2143 pr-url: https://github.com/nodejs-private/node-private/pull/248 2144 description: Added `unknownProtocolTimeout` option with a default of 10000. 2145 - version: v10.21.0 2146 pr-url: https://github.com/nodejs-private/node-private/pull/204 2147 description: Added `maxSettings` option with a default of 32. 2148 - version: v8.9.3 2149 pr-url: https://github.com/nodejs/node/pull/17105 2150 description: Added the `maxOutstandingPings` option with a default limit of 2151 10. 2152 - version: v8.9.3 2153 pr-url: https://github.com/nodejs/node/pull/16676 2154 description: Added the `maxHeaderListPairs` option with a default limit of 2155 128 header pairs. 2156--> 2157 2158* `authority` {string|URL} 2159* `options` {Object} 2160 * `maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size 2161 for deflating header fields. **Default:** `4Kib`. 2162 * `maxSettings` {number} Sets the maximum number of settings entries per 2163 `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`. 2164 * `maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` 2165 is permitted to use. The value is expressed in terms of number of megabytes, 2166 e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. 2167 This is a credit based limit, existing `Http2Stream`s may cause this 2168 limit to be exceeded, but new `Http2Stream` instances will be rejected 2169 while this limit is exceeded. The current number of `Http2Stream` sessions, 2170 the current memory use of the header compression tables, current data 2171 queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all 2172 counted towards the current limit. **Default:** `10`. 2173 * `maxHeaderListPairs` {number} Sets the maximum number of header entries. 2174 The minimum value is `1`. **Default:** `128`. 2175 * `maxOutstandingPings` {number} Sets the maximum number of outstanding, 2176 unacknowledged pings. **Default:** `10`. 2177 * `maxReservedRemoteStreams` {number} Sets the maximum number of reserved push 2178 streams the client will accept at any given time. Once the current number of 2179 currently reserved push streams exceeds reaches this limit, new push streams 2180 sent by the server will be automatically rejected. 2181 * `maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a 2182 serialized, compressed block of headers. Attempts to send headers that 2183 exceed this limit will result in a `'frameError'` event being emitted 2184 and the stream being closed and destroyed. 2185 * `paddingStrategy` {number} Identifies the strategy used for determining the 2186 amount of padding to use for `HEADERS` and `DATA` frames. **Default:** 2187 `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of: 2188 * `http2.constants.PADDING_STRATEGY_NONE` - Specifies that no padding is 2189 to be applied. 2190 * `http2.constants.PADDING_STRATEGY_MAX` - Specifies that the maximum 2191 amount of padding, as determined by the internal implementation, is to 2192 be applied. 2193 * `http2.constants.PADDING_STRATEGY_CALLBACK` - Specifies that the user 2194 provided `options.selectPadding()` callback is to be used to determine 2195 the amount of padding. 2196 * `http2.constants.PADDING_STRATEGY_ALIGNED` - Will *attempt* to apply 2197 enough padding to ensure that the total frame length, including the 2198 9-byte header, is a multiple of 8. For each frame, however, there is a 2199 maximum allowed number of padding bytes that is determined by current 2200 flow control state and settings. If this maximum is less than the 2201 calculated amount needed to ensure alignment, the maximum will be used 2202 and the total frame length will *not* necessarily be aligned at 8 bytes. 2203 * `peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent 2204 streams for the remote peer as if a `SETTINGS` frame had been received. Will 2205 be overridden if the remote peer sets its own value for 2206 `maxConcurrentStreams`. **Default:** `100`. 2207 * `selectPadding` {Function} When `options.paddingStrategy` is equal to 2208 `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function 2209 used to determine the padding. See [Using `options.selectPadding()`][]. 2210 * `settings` {HTTP/2 Settings Object} The initial settings to send to the 2211 remote peer upon connection. 2212 * `createConnection` {Function} An optional callback that receives the `URL` 2213 instance passed to `connect` and the `options` object, and returns any 2214 [`Duplex`][] stream that is to be used as the connection for this session. 2215 * ...: Any [`net.connect()`][] or [`tls.connect()`][] options can be provided. 2216 * `unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that 2217 a server should wait when an [`'unknownProtocol'`][] event is emitted. If 2218 the socket has not been destroyed by that time the server will destroy it. 2219 **Default:** `10000`. 2220* `listener` {Function} 2221* Returns: {ClientHttp2Session} 2222 2223Returns a `ClientHttp2Session` instance. 2224 2225```js 2226const http2 = require('http2'); 2227const client = http2.connect('https://localhost:1234'); 2228 2229/* Use the client */ 2230 2231client.close(); 2232``` 2233 2234### http2.constants 2235<!-- YAML 2236added: v8.4.0 2237--> 2238 2239#### Error Codes for RST_STREAM and GOAWAY 2240<a id="error_codes"></a> 2241 2242| Value | Name | Constant | 2243|--------|---------------------|-----------------------------------------------| 2244| `0x00` | No Error | `http2.constants.NGHTTP2_NO_ERROR` | 2245| `0x01` | Protocol Error | `http2.constants.NGHTTP2_PROTOCOL_ERROR` | 2246| `0x02` | Internal Error | `http2.constants.NGHTTP2_INTERNAL_ERROR` | 2247| `0x03` | Flow Control Error | `http2.constants.NGHTTP2_FLOW_CONTROL_ERROR` | 2248| `0x04` | Settings Timeout | `http2.constants.NGHTTP2_SETTINGS_TIMEOUT` | 2249| `0x05` | Stream Closed | `http2.constants.NGHTTP2_STREAM_CLOSED` | 2250| `0x06` | Frame Size Error | `http2.constants.NGHTTP2_FRAME_SIZE_ERROR` | 2251| `0x07` | Refused Stream | `http2.constants.NGHTTP2_REFUSED_STREAM` | 2252| `0x08` | Cancel | `http2.constants.NGHTTP2_CANCEL` | 2253| `0x09` | Compression Error | `http2.constants.NGHTTP2_COMPRESSION_ERROR` | 2254| `0x0a` | Connect Error | `http2.constants.NGHTTP2_CONNECT_ERROR` | 2255| `0x0b` | Enhance Your Calm | `http2.constants.NGHTTP2_ENHANCE_YOUR_CALM` | 2256| `0x0c` | Inadequate Security | `http2.constants.NGHTTP2_INADEQUATE_SECURITY` | 2257| `0x0d` | HTTP/1.1 Required | `http2.constants.NGHTTP2_HTTP_1_1_REQUIRED` | 2258 2259The `'timeout'` event is emitted when there is no activity on the Server for 2260a given number of milliseconds set using `http2server.setTimeout()`. 2261 2262### http2.getDefaultSettings() 2263<!-- YAML 2264added: v8.4.0 2265--> 2266 2267* Returns: {HTTP/2 Settings Object} 2268 2269Returns an object containing the default settings for an `Http2Session` 2270instance. This method returns a new object instance every time it is called 2271so instances returned may be safely modified for use. 2272 2273### http2.getPackedSettings(settings) 2274<!-- YAML 2275added: v8.4.0 2276--> 2277 2278* `settings` {HTTP/2 Settings Object} 2279* Returns: {Buffer} 2280 2281Returns a `Buffer` instance containing serialized representation of the given 2282HTTP/2 settings as specified in the [HTTP/2][] specification. This is intended 2283for use with the `HTTP2-Settings` header field. 2284 2285```js 2286const http2 = require('http2'); 2287 2288const packed = http2.getPackedSettings({ enablePush: false }); 2289 2290console.log(packed.toString('base64')); 2291// Prints: AAIAAAAA 2292``` 2293 2294### http2.getUnpackedSettings(buf) 2295<!-- YAML 2296added: v8.4.0 2297--> 2298 2299* `buf` {Buffer|Uint8Array} The packed settings. 2300* Returns: {HTTP/2 Settings Object} 2301 2302Returns a [HTTP/2 Settings Object][] containing the deserialized settings from 2303the given `Buffer` as generated by `http2.getPackedSettings()`. 2304 2305### Headers Object 2306 2307Headers are represented as own-properties on JavaScript objects. The property 2308keys will be serialized to lower-case. Property values should be strings (if 2309they are not they will be coerced to strings) or an `Array` of strings (in order 2310to send more than one value per header field). 2311 2312```js 2313const headers = { 2314 ':status': '200', 2315 'content-type': 'text-plain', 2316 'ABC': ['has', 'more', 'than', 'one', 'value'] 2317}; 2318 2319stream.respond(headers); 2320``` 2321 2322Header objects passed to callback functions will have a `null` prototype. This 2323means that normal JavaScript object methods such as 2324`Object.prototype.toString()` and `Object.prototype.hasOwnProperty()` will 2325not work. 2326 2327For incoming headers: 2328* The `:status` header is converted to `number`. 2329* Duplicates of `:status`, `:method`, `:authority`, `:scheme`, `:path`, 2330`:protocol`, `age`, `authorization`, `access-control-allow-credentials`, 2331`access-control-max-age`, `access-control-request-method`, `content-encoding`, 2332`content-language`, `content-length`, `content-location`, `content-md5`, 2333`content-range`, `content-type`, `date`, `dnt`, `etag`, `expires`, `from`, 2334`if-match`, `if-modified-since`, `if-none-match`, `if-range`, 2335`if-unmodified-since`, `last-modified`, `location`, `max-forwards`, 2336`proxy-authorization`, `range`, `referer`,`retry-after`, `tk`, 2337`upgrade-insecure-requests`, `user-agent` or `x-content-type-options` are 2338discarded. 2339* `set-cookie` is always an array. Duplicates are added to the array. 2340* For duplicate `cookie` headers, the values are joined together with '; '. 2341* For all other headers, the values are joined together with ', '. 2342 2343```js 2344const http2 = require('http2'); 2345const server = http2.createServer(); 2346server.on('stream', (stream, headers) => { 2347 console.log(headers[':path']); 2348 console.log(headers.ABC); 2349}); 2350``` 2351 2352### Settings Object 2353<!-- YAML 2354added: v8.4.0 2355changes: 2356 - version: v8.9.3 2357 pr-url: https://github.com/nodejs/node/pull/16676 2358 description: The `maxHeaderListSize` setting is now strictly enforced. 2359--> 2360The `http2.getDefaultSettings()`, `http2.getPackedSettings()`, 2361`http2.createServer()`, `http2.createSecureServer()`, 2362`http2session.settings()`, `http2session.localSettings`, and 2363`http2session.remoteSettings` APIs either return or receive as input an 2364object that defines configuration settings for an `Http2Session` object. 2365These objects are ordinary JavaScript objects containing the following 2366properties. 2367 2368* `headerTableSize` {number} Specifies the maximum number of bytes used for 2369 header compression. The minimum allowed value is 0. The maximum allowed value 2370 is 2<sup>32</sup>-1. **Default:** `4,096 octets`. 2371* `enablePush` {boolean} Specifies `true` if HTTP/2 Push Streams are to be 2372 permitted on the `Http2Session` instances. 2373* `initialWindowSize` {number} Specifies the *senders* initial window size 2374 for stream-level flow control. The minimum allowed value is 0. The maximum 2375 allowed value is 2<sup>32</sup>-1. **Default:** `65,535 bytes`. 2376* `maxFrameSize` {number} Specifies the size of the largest frame payload. 2377 The minimum allowed value is 16,384. The maximum allowed value 2378 is 2<sup>24</sup>-1. **Default:** `16,384 bytes`. 2379* `maxConcurrentStreams` {number} Specifies the maximum number of concurrent 2380 streams permitted on an `Http2Session`. There is no default value which 2381 implies, at least theoretically, 2<sup>31</sup>-1 streams may be open 2382 concurrently at any given time in an `Http2Session`. The minimum value 2383 is 0. The maximum allowed value is 2<sup>31</sup>-1. 2384* `maxHeaderListSize` {number} Specifies the maximum size (uncompressed octets) 2385 of header list that will be accepted. The minimum allowed value is 0. The 2386 maximum allowed value is 2<sup>32</sup>-1. **Default:** `65535`. 2387* `enableConnectProtocol`{boolean} Specifies `true` if the "Extended Connect 2388 Protocol" defined by [RFC 8441][] is to be enabled. This setting is only 2389 meaningful if sent by the server. Once the `enableConnectProtocol` setting 2390 has been enabled for a given `Http2Session`, it cannot be disabled. 2391 2392All additional properties on the settings object are ignored. 2393 2394### Using `options.selectPadding()` 2395 2396When `options.paddingStrategy` is equal to 2397`http2.constants.PADDING_STRATEGY_CALLBACK`, the HTTP/2 implementation will 2398consult the `options.selectPadding()` callback function, if provided, to 2399determine the specific amount of padding to use per `HEADERS` and `DATA` frame. 2400 2401The `options.selectPadding()` function receives two numeric arguments, 2402`frameLen` and `maxFrameLen` and must return a number `N` such that 2403`frameLen <= N <= maxFrameLen`. 2404 2405```js 2406const http2 = require('http2'); 2407const server = http2.createServer({ 2408 paddingStrategy: http2.constants.PADDING_STRATEGY_CALLBACK, 2409 selectPadding(frameLen, maxFrameLen) { 2410 return maxFrameLen; 2411 } 2412}); 2413``` 2414 2415The `options.selectPadding()` function is invoked once for *every* `HEADERS` and 2416`DATA` frame. This has a definite noticeable impact on performance. 2417 2418### Error Handling 2419 2420There are several types of error conditions that may arise when using the 2421`http2` module: 2422 2423Validation errors occur when an incorrect argument, option, or setting value is 2424passed in. These will always be reported by a synchronous `throw`. 2425 2426State errors occur when an action is attempted at an incorrect time (for 2427instance, attempting to send data on a stream after it has closed). These will 2428be reported using either a synchronous `throw` or via an `'error'` event on 2429the `Http2Stream`, `Http2Session` or HTTP/2 Server objects, depending on where 2430and when the error occurs. 2431 2432Internal errors occur when an HTTP/2 session fails unexpectedly. These will be 2433reported via an `'error'` event on the `Http2Session` or HTTP/2 Server objects. 2434 2435Protocol errors occur when various HTTP/2 protocol constraints are violated. 2436These will be reported using either a synchronous `throw` or via an `'error'` 2437event on the `Http2Stream`, `Http2Session` or HTTP/2 Server objects, depending 2438on where and when the error occurs. 2439 2440### Invalid character handling in header names and values 2441 2442The HTTP/2 implementation applies stricter handling of invalid characters in 2443HTTP header names and values than the HTTP/1 implementation. 2444 2445Header field names are *case-insensitive* and are transmitted over the wire 2446strictly as lower-case strings. The API provided by Node.js allows header 2447names to be set as mixed-case strings (e.g. `Content-Type`) but will convert 2448those to lower-case (e.g. `content-type`) upon transmission. 2449 2450Header field-names *must only* contain one or more of the following ASCII 2451characters: `a`-`z`, `A`-`Z`, `0`-`9`, `!`, `#`, `$`, `%`, `&`, `'`, `*`, `+`, 2452`-`, `.`, `^`, `_`, `` ` `` (backtick), `|`, and `~`. 2453 2454Using invalid characters within an HTTP header field name will cause the 2455stream to be closed with a protocol error being reported. 2456 2457Header field values are handled with more leniency but *should* not contain 2458new-line or carriage return characters and *should* be limited to US-ASCII 2459characters, per the requirements of the HTTP specification. 2460 2461### Push streams on the client 2462 2463To receive pushed streams on the client, set a listener for the `'stream'` 2464event on the `ClientHttp2Session`: 2465 2466```js 2467const http2 = require('http2'); 2468 2469const client = http2.connect('http://localhost'); 2470 2471client.on('stream', (pushedStream, requestHeaders) => { 2472 pushedStream.on('push', (responseHeaders) => { 2473 // process response headers 2474 }); 2475 pushedStream.on('data', (chunk) => { /* handle pushed data */ }); 2476}); 2477 2478const req = client.request({ ':path': '/' }); 2479``` 2480 2481### Supporting the CONNECT method 2482 2483The `CONNECT` method is used to allow an HTTP/2 server to be used as a proxy 2484for TCP/IP connections. 2485 2486A simple TCP Server: 2487```js 2488const net = require('net'); 2489 2490const server = net.createServer((socket) => { 2491 let name = ''; 2492 socket.setEncoding('utf8'); 2493 socket.on('data', (chunk) => name += chunk); 2494 socket.on('end', () => socket.end(`hello ${name}`)); 2495}); 2496 2497server.listen(8000); 2498``` 2499 2500An HTTP/2 CONNECT proxy: 2501 2502```js 2503const http2 = require('http2'); 2504const { NGHTTP2_REFUSED_STREAM } = http2.constants; 2505const net = require('net'); 2506 2507const proxy = http2.createServer(); 2508proxy.on('stream', (stream, headers) => { 2509 if (headers[':method'] !== 'CONNECT') { 2510 // Only accept CONNECT requests 2511 stream.close(NGHTTP2_REFUSED_STREAM); 2512 return; 2513 } 2514 const auth = new URL(`tcp://${headers[':authority']}`); 2515 // It's a very good idea to verify that hostname and port are 2516 // things this proxy should be connecting to. 2517 const socket = net.connect(auth.port, auth.hostname, () => { 2518 stream.respond(); 2519 socket.pipe(stream); 2520 stream.pipe(socket); 2521 }); 2522 socket.on('error', (error) => { 2523 stream.close(http2.constants.NGHTTP2_CONNECT_ERROR); 2524 }); 2525}); 2526 2527proxy.listen(8001); 2528``` 2529 2530An HTTP/2 CONNECT client: 2531 2532```js 2533const http2 = require('http2'); 2534 2535const client = http2.connect('http://localhost:8001'); 2536 2537// Must not specify the ':path' and ':scheme' headers 2538// for CONNECT requests or an error will be thrown. 2539const req = client.request({ 2540 ':method': 'CONNECT', 2541 ':authority': `localhost:${port}` 2542}); 2543 2544req.on('response', (headers) => { 2545 console.log(headers[http2.constants.HTTP2_HEADER_STATUS]); 2546}); 2547let data = ''; 2548req.setEncoding('utf8'); 2549req.on('data', (chunk) => data += chunk); 2550req.on('end', () => { 2551 console.log(`The server says: ${data}`); 2552 client.close(); 2553}); 2554req.end('Jane'); 2555``` 2556 2557### The Extended CONNECT Protocol 2558 2559[RFC 8441][] defines an "Extended CONNECT Protocol" extension to HTTP/2 that 2560may be used to bootstrap the use of an `Http2Stream` using the `CONNECT` 2561method as a tunnel for other communication protocols (such as WebSockets). 2562 2563The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using 2564the `enableConnectProtocol` setting: 2565 2566```js 2567const http2 = require('http2'); 2568const settings = { enableConnectProtocol: true }; 2569const server = http2.createServer({ settings }); 2570``` 2571 2572Once the client receives the `SETTINGS` frame from the server indicating that 2573the extended CONNECT may be used, it may send `CONNECT` requests that use the 2574`':protocol'` HTTP/2 pseudo-header: 2575 2576```js 2577const http2 = require('http2'); 2578const client = http2.connect('http://localhost:8080'); 2579client.on('remoteSettings', (settings) => { 2580 if (settings.enableConnectProtocol) { 2581 const req = client.request({ ':method': 'CONNECT', ':protocol': 'foo' }); 2582 // ... 2583 } 2584}); 2585``` 2586 2587## Compatibility API 2588 2589The Compatibility API has the goal of providing a similar developer experience 2590of HTTP/1 when using HTTP/2, making it possible to develop applications 2591that support both [HTTP/1][] and HTTP/2. This API targets only the 2592**public API** of the [HTTP/1][]. However many modules use internal 2593methods or state, and those _are not supported_ as it is a completely 2594different implementation. 2595 2596The following example creates an HTTP/2 server using the compatibility 2597API: 2598 2599```js 2600const http2 = require('http2'); 2601const server = http2.createServer((req, res) => { 2602 res.setHeader('Content-Type', 'text/html'); 2603 res.setHeader('X-Foo', 'bar'); 2604 res.writeHead(200, { 'Content-Type': 'text/plain' }); 2605 res.end('ok'); 2606}); 2607``` 2608 2609In order to create a mixed [HTTPS][] and HTTP/2 server, refer to the 2610[ALPN negotiation][] section. 2611Upgrading from non-tls HTTP/1 servers is not supported. 2612 2613The HTTP/2 compatibility API is composed of [`Http2ServerRequest`]() and 2614[`Http2ServerResponse`](). They aim at API compatibility with HTTP/1, but 2615they do not hide the differences between the protocols. As an example, 2616the status message for HTTP codes is ignored. 2617 2618### ALPN negotiation 2619 2620ALPN negotiation allows supporting both [HTTPS][] and HTTP/2 over 2621the same socket. The `req` and `res` objects can be either HTTP/1 or 2622HTTP/2, and an application **must** restrict itself to the public API of 2623[HTTP/1][], and detect if it is possible to use the more advanced 2624features of HTTP/2. 2625 2626The following example creates a server that supports both protocols: 2627 2628```js 2629const { createSecureServer } = require('http2'); 2630const { readFileSync } = require('fs'); 2631 2632const cert = readFileSync('./cert.pem'); 2633const key = readFileSync('./key.pem'); 2634 2635const server = createSecureServer( 2636 { cert, key, allowHTTP1: true }, 2637 onRequest 2638).listen(4443); 2639 2640function onRequest(req, res) { 2641 // detects if it is a HTTPS request or HTTP/2 2642 const { socket: { alpnProtocol } } = req.httpVersion === '2.0' ? 2643 req.stream.session : req; 2644 res.writeHead(200, { 'content-type': 'application/json' }); 2645 res.end(JSON.stringify({ 2646 alpnProtocol, 2647 httpVersion: req.httpVersion 2648 })); 2649} 2650``` 2651 2652The `'request'` event works identically on both [HTTPS][] and 2653HTTP/2. 2654 2655### Class: http2.Http2ServerRequest 2656<!-- YAML 2657added: v8.4.0 2658--> 2659 2660A `Http2ServerRequest` object is created by [`http2.Server`][] or 2661[`http2.SecureServer`][] and passed as the first argument to the 2662[`'request'`][] event. It may be used to access a request status, headers, and 2663data. 2664 2665It implements the [Readable Stream][] interface, as well as the 2666following additional events, methods, and properties. 2667 2668#### Event: 'aborted' 2669<!-- YAML 2670added: v8.4.0 2671--> 2672 2673The `'aborted'` event is emitted whenever a `Http2ServerRequest` instance is 2674abnormally aborted in mid-communication. 2675 2676The `'aborted'` event will only be emitted if the `Http2ServerRequest` writable 2677side has not been ended. 2678 2679#### Event: 'close' 2680<!-- YAML 2681added: v8.4.0 2682--> 2683 2684Indicates that the underlying [`Http2Stream`][] was closed. 2685Just like `'end'`, this event occurs only once per response. 2686 2687#### request.aborted 2688<!-- YAML 2689added: v10.1.0 2690--> 2691 2692* {boolean} 2693 2694The `request.aborted` property will be `true` if the request has 2695been aborted. 2696 2697#### request.authority 2698<!-- YAML 2699added: v8.4.0 2700--> 2701 2702* {string} 2703 2704The request authority pseudo header field. It can also be accessed via 2705`req.headers[':authority']`. 2706 2707#### request.destroy([error]) 2708<!-- YAML 2709added: v8.4.0 2710--> 2711 2712* `error` {Error} 2713 2714Calls `destroy()` on the [`Http2Stream`][] that received 2715the [`Http2ServerRequest`][]. If `error` is provided, an `'error'` event 2716is emitted and `error` is passed as an argument to any listeners on the event. 2717 2718It does nothing if the stream was already destroyed. 2719 2720#### request.headers 2721<!-- YAML 2722added: v8.4.0 2723--> 2724 2725* {Object} 2726 2727The request/response headers object. 2728 2729Key-value pairs of header names and values. Header names are lower-cased. 2730 2731```js 2732// Prints something like: 2733// 2734// { 'user-agent': 'curl/7.22.0', 2735// host: '127.0.0.1:8000', 2736// accept: '*/*' } 2737console.log(request.headers); 2738``` 2739 2740See [HTTP/2 Headers Object][]. 2741 2742In HTTP/2, the request path, hostname, protocol, and method are represented as 2743special headers prefixed with the `:` character (e.g. `':path'`). These special 2744headers will be included in the `request.headers` object. Care must be taken not 2745to inadvertently modify these special headers or errors may occur. For instance, 2746removing all headers from the request will cause errors to occur: 2747 2748```js 2749removeAllHeaders(request.headers); 2750assert(request.url); // Fails because the :path header has been removed 2751``` 2752 2753#### request.httpVersion 2754<!-- YAML 2755added: v8.4.0 2756--> 2757 2758* {string} 2759 2760In case of server request, the HTTP version sent by the client. In the case of 2761client response, the HTTP version of the connected-to server. Returns 2762`'2.0'`. 2763 2764Also `message.httpVersionMajor` is the first integer and 2765`message.httpVersionMinor` is the second. 2766 2767#### request.method 2768<!-- YAML 2769added: v8.4.0 2770--> 2771 2772* {string} 2773 2774The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. 2775 2776#### request.rawHeaders 2777<!-- YAML 2778added: v8.4.0 2779--> 2780 2781* {string[]} 2782 2783The raw request/response headers list exactly as they were received. 2784 2785Note that the keys and values are in the same list. It is *not* a 2786list of tuples. So, the even-numbered offsets are key values, and the 2787odd-numbered offsets are the associated values. 2788 2789Header names are not lowercased, and duplicates are not merged. 2790 2791```js 2792// Prints something like: 2793// 2794// [ 'user-agent', 2795// 'this is invalid because there can be only one', 2796// 'User-Agent', 2797// 'curl/7.22.0', 2798// 'Host', 2799// '127.0.0.1:8000', 2800// 'ACCEPT', 2801// '*/*' ] 2802console.log(request.rawHeaders); 2803``` 2804 2805#### request.rawTrailers 2806<!-- YAML 2807added: v8.4.0 2808--> 2809 2810* {string[]} 2811 2812The raw request/response trailer keys and values exactly as they were 2813received. Only populated at the `'end'` event. 2814 2815#### request.scheme 2816<!-- YAML 2817added: v8.4.0 2818--> 2819 2820* {string} 2821 2822The request scheme pseudo header field indicating the scheme 2823portion of the target URL. 2824 2825#### request.setTimeout(msecs, callback) 2826<!-- YAML 2827added: v8.4.0 2828--> 2829 2830* `msecs` {number} 2831* `callback` {Function} 2832* Returns: {http2.Http2ServerRequest} 2833 2834Sets the [`Http2Stream`]()'s timeout value to `msecs`. If a callback is 2835provided, then it is added as a listener on the `'timeout'` event on 2836the response object. 2837 2838If no `'timeout'` listener is added to the request, the response, or 2839the server, then [`Http2Stream`]()s are destroyed when they time out. If a 2840handler is assigned to the request, the response, or the server's `'timeout'` 2841events, timed out sockets must be handled explicitly. 2842 2843#### request.socket 2844<!-- YAML 2845added: v8.4.0 2846--> 2847 2848* {net.Socket|tls.TLSSocket} 2849 2850Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but 2851applies getters, setters, and methods based on HTTP/2 logic. 2852 2853`destroyed`, `readable`, and `writable` properties will be retrieved from and 2854set on `request.stream`. 2855 2856`destroy`, `emit`, `end`, `on` and `once` methods will be called on 2857`request.stream`. 2858 2859`setTimeout` method will be called on `request.stream.session`. 2860 2861`pause`, `read`, `resume`, and `write` will throw an error with code 2862`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See [`Http2Session` and Sockets][] for 2863more information. 2864 2865All other interactions will be routed directly to the socket. With TLS support, 2866use [`request.socket.getPeerCertificate()`][] to obtain the client's 2867authentication details. 2868 2869#### request.stream 2870<!-- YAML 2871added: v8.4.0 2872--> 2873 2874* {Http2Stream} 2875 2876The [`Http2Stream`][] object backing the request. 2877 2878#### request.trailers 2879<!-- YAML 2880added: v8.4.0 2881--> 2882 2883* {Object} 2884 2885The request/response trailers object. Only populated at the `'end'` event. 2886 2887#### request.url 2888<!-- YAML 2889added: v8.4.0 2890--> 2891 2892* {string} 2893 2894Request URL string. This contains only the URL that is 2895present in the actual HTTP request. If the request is: 2896 2897```txt 2898GET /status?name=ryan HTTP/1.1\r\n 2899Accept: text/plain\r\n 2900\r\n 2901``` 2902 2903Then `request.url` will be: 2904 2905<!-- eslint-disable semi --> 2906```js 2907'/status?name=ryan' 2908``` 2909 2910To parse the url into its parts `require('url').parse(request.url)` 2911can be used: 2912 2913```txt 2914$ node 2915> require('url').parse('/status?name=ryan') 2916Url { 2917 protocol: null, 2918 slashes: null, 2919 auth: null, 2920 host: null, 2921 port: null, 2922 hostname: null, 2923 hash: null, 2924 search: '?name=ryan', 2925 query: 'name=ryan', 2926 pathname: '/status', 2927 path: '/status?name=ryan', 2928 href: '/status?name=ryan' } 2929``` 2930 2931To extract the parameters from the query string, the 2932`require('querystring').parse` function can be used, or 2933`true` can be passed as the second argument to `require('url').parse`. 2934 2935```txt 2936$ node 2937> require('url').parse('/status?name=ryan', true) 2938Url { 2939 protocol: null, 2940 slashes: null, 2941 auth: null, 2942 host: null, 2943 port: null, 2944 hostname: null, 2945 hash: null, 2946 search: '?name=ryan', 2947 query: { name: 'ryan' }, 2948 pathname: '/status', 2949 path: '/status?name=ryan', 2950 href: '/status?name=ryan' } 2951``` 2952 2953### Class: http2.Http2ServerResponse 2954<!-- YAML 2955added: v8.4.0 2956--> 2957 2958This object is created internally by an HTTP server, not by the user. It is 2959passed as the second parameter to the [`'request'`][] event. 2960 2961The response inherits from [Stream][], and additionally implements the 2962following: 2963 2964#### Event: 'close' 2965<!-- YAML 2966added: v8.4.0 2967--> 2968 2969Indicates that the underlying [`Http2Stream`]() was terminated before 2970[`response.end()`][] was called or able to flush. 2971 2972#### Event: 'finish' 2973<!-- YAML 2974added: v8.4.0 2975--> 2976 2977Emitted when the response has been sent. More specifically, this event is 2978emitted when the last segment of the response headers and body have been 2979handed off to the HTTP/2 multiplexing for transmission over the network. It 2980does not imply that the client has received anything yet. 2981 2982After this event, no more events will be emitted on the response object. 2983 2984#### response.addTrailers(headers) 2985<!-- YAML 2986added: v8.4.0 2987--> 2988 2989* `headers` {Object} 2990 2991This method adds HTTP trailing headers (a header but at the end of the 2992message) to the response. 2993 2994Attempting to set a header field name or value that contains invalid characters 2995will result in a [`TypeError`][] being thrown. 2996 2997#### response.connection 2998<!-- YAML 2999added: v8.4.0 3000--> 3001 3002* {net.Socket|tls.TLSSocket} 3003 3004See [`response.socket`][]. 3005 3006#### response.end([data][, encoding][, callback]) 3007<!-- YAML 3008added: v8.4.0 3009changes: 3010 - version: v10.0.0 3011 pr-url: https://github.com/nodejs/node/pull/18780 3012 description: This method now returns a reference to `ServerResponse`. 3013--> 3014 3015* `data` {string|Buffer} 3016* `encoding` {string} 3017* `callback` {Function} 3018* Returns: {this} 3019 3020This method signals to the server that all of the response headers and body 3021have been sent; that server should consider this message complete. 3022The method, `response.end()`, MUST be called on each response. 3023 3024If `data` is specified, it is equivalent to calling 3025[`response.write(data, encoding)`][] followed by `response.end(callback)`. 3026 3027If `callback` is specified, it will be called when the response stream 3028is finished. 3029 3030#### response.finished 3031<!-- YAML 3032added: v8.4.0 3033--> 3034 3035* {boolean} 3036 3037Boolean value that indicates whether the response has completed. Starts 3038as `false`. After [`response.end()`][] executes, the value will be `true`. 3039 3040#### response.getHeader(name) 3041<!-- YAML 3042added: v8.4.0 3043--> 3044 3045* `name` {string} 3046* Returns: {string} 3047 3048Reads out a header that has already been queued but not sent to the client. 3049Note that the name is case insensitive. 3050 3051```js 3052const contentType = response.getHeader('content-type'); 3053``` 3054 3055#### response.getHeaderNames() 3056<!-- YAML 3057added: v8.4.0 3058--> 3059 3060* Returns: {string[]} 3061 3062Returns an array containing the unique names of the current outgoing headers. 3063All header names are lowercase. 3064 3065```js 3066response.setHeader('Foo', 'bar'); 3067response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); 3068 3069const headerNames = response.getHeaderNames(); 3070// headerNames === ['foo', 'set-cookie'] 3071``` 3072 3073#### response.getHeaders() 3074<!-- YAML 3075added: v8.4.0 3076--> 3077 3078* Returns: {Object} 3079 3080Returns a shallow copy of the current outgoing headers. Since a shallow copy 3081is used, array values may be mutated without additional calls to various 3082header-related http module methods. The keys of the returned object are the 3083header names and the values are the respective header values. All header names 3084are lowercase. 3085 3086The object returned by the `response.getHeaders()` method _does not_ 3087prototypically inherit from the JavaScript `Object`. This means that typical 3088`Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others 3089are not defined and *will not work*. 3090 3091```js 3092response.setHeader('Foo', 'bar'); 3093response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); 3094 3095const headers = response.getHeaders(); 3096// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } 3097``` 3098 3099#### response.hasHeader(name) 3100<!-- YAML 3101added: v8.4.0 3102--> 3103 3104* `name` {string} 3105* Returns: {boolean} 3106 3107Returns `true` if the header identified by `name` is currently set in the 3108outgoing headers. Note that the header name matching is case-insensitive. 3109 3110```js 3111const hasContentType = response.hasHeader('content-type'); 3112``` 3113 3114#### response.headersSent 3115<!-- YAML 3116added: v8.4.0 3117--> 3118 3119* {boolean} 3120 3121True if headers were sent, false otherwise (read-only). 3122 3123#### response.removeHeader(name) 3124<!-- YAML 3125added: v8.4.0 3126--> 3127 3128* `name` {string} 3129 3130Removes a header that has been queued for implicit sending. 3131 3132```js 3133response.removeHeader('Content-Encoding'); 3134``` 3135 3136#### response.sendDate 3137<!-- YAML 3138added: v8.4.0 3139--> 3140 3141* {boolean} 3142 3143When true, the Date header will be automatically generated and sent in 3144the response if it is not already present in the headers. Defaults to true. 3145 3146This should only be disabled for testing; HTTP requires the Date header 3147in responses. 3148 3149#### response.setHeader(name, value) 3150<!-- YAML 3151added: v8.4.0 3152--> 3153 3154* `name` {string} 3155* `value` {string|string[]} 3156 3157Sets a single header value for implicit headers. If this header already exists 3158in the to-be-sent headers, its value will be replaced. Use an array of strings 3159here to send multiple headers with the same name. 3160 3161```js 3162response.setHeader('Content-Type', 'text/html'); 3163``` 3164 3165or 3166 3167```js 3168response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); 3169``` 3170 3171Attempting to set a header field name or value that contains invalid characters 3172will result in a [`TypeError`][] being thrown. 3173 3174When headers have been set with [`response.setHeader()`][], they will be merged 3175with any headers passed to [`response.writeHead()`][], with the headers passed 3176to [`response.writeHead()`][] given precedence. 3177 3178```js 3179// returns content-type = text/plain 3180const server = http2.createServer((req, res) => { 3181 res.setHeader('Content-Type', 'text/html'); 3182 res.setHeader('X-Foo', 'bar'); 3183 res.writeHead(200, { 'Content-Type': 'text/plain' }); 3184 res.end('ok'); 3185}); 3186``` 3187 3188#### response.setTimeout(msecs[, callback]) 3189<!-- YAML 3190added: v8.4.0 3191--> 3192 3193* `msecs` {number} 3194* `callback` {Function} 3195* Returns: {http2.Http2ServerResponse} 3196 3197Sets the [`Http2Stream`]()'s timeout value to `msecs`. If a callback is 3198provided, then it is added as a listener on the `'timeout'` event on 3199the response object. 3200 3201If no `'timeout'` listener is added to the request, the response, or 3202the server, then [`Http2Stream`]()s are destroyed when they time out. If a 3203handler is assigned to the request, the response, or the server's `'timeout'` 3204events, timed out sockets must be handled explicitly. 3205 3206#### response.socket 3207<!-- YAML 3208added: v8.4.0 3209--> 3210 3211* {net.Socket|tls.TLSSocket} 3212 3213Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but 3214applies getters, setters, and methods based on HTTP/2 logic. 3215 3216`destroyed`, `readable`, and `writable` properties will be retrieved from and 3217set on `response.stream`. 3218 3219`destroy`, `emit`, `end`, `on` and `once` methods will be called on 3220`response.stream`. 3221 3222`setTimeout` method will be called on `response.stream.session`. 3223 3224`pause`, `read`, `resume`, and `write` will throw an error with code 3225`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See [`Http2Session` and Sockets][] for 3226more information. 3227 3228All other interactions will be routed directly to the socket. 3229 3230```js 3231const http2 = require('http2'); 3232const server = http2.createServer((req, res) => { 3233 const ip = req.socket.remoteAddress; 3234 const port = req.socket.remotePort; 3235 res.end(`Your IP address is ${ip} and your source port is ${port}.`); 3236}).listen(3000); 3237``` 3238 3239#### response.statusCode 3240<!-- YAML 3241added: v8.4.0 3242--> 3243 3244* {number} 3245 3246When using implicit headers (not calling [`response.writeHead()`][] explicitly), 3247this property controls the status code that will be sent to the client when 3248the headers get flushed. 3249 3250```js 3251response.statusCode = 404; 3252``` 3253 3254After response header was sent to the client, this property indicates the 3255status code which was sent out. 3256 3257#### response.statusMessage 3258<!-- YAML 3259added: v8.4.0 3260--> 3261 3262* {string} 3263 3264Status message is not supported by HTTP/2 (RFC7540 8.1.2.4). It returns 3265an empty string. 3266 3267#### response.stream 3268<!-- YAML 3269added: v8.4.0 3270--> 3271 3272* {Http2Stream} 3273 3274The [`Http2Stream`][] object backing the response. 3275 3276#### response.write(chunk[, encoding][, callback]) 3277<!-- YAML 3278added: v8.4.0 3279--> 3280 3281* `chunk` {string|Buffer} 3282* `encoding` {string} 3283* `callback` {Function} 3284* Returns: {boolean} 3285 3286If this method is called and [`response.writeHead()`][] has not been called, 3287it will switch to implicit header mode and flush the implicit headers. 3288 3289This sends a chunk of the response body. This method may 3290be called multiple times to provide successive parts of the body. 3291 3292Note that in the `http` module, the response body is omitted when the 3293request is a HEAD request. Similarly, the `204` and `304` responses 3294_must not_ include a message body. 3295 3296`chunk` can be a string or a buffer. If `chunk` is a string, 3297the second parameter specifies how to encode it into a byte stream. 3298By default the `encoding` is `'utf8'`. `callback` will be called when this chunk 3299of data is flushed. 3300 3301This is the raw HTTP body and has nothing to do with higher-level multi-part 3302body encodings that may be used. 3303 3304The first time [`response.write()`][] is called, it will send the buffered 3305header information and the first chunk of the body to the client. The second 3306time [`response.write()`][] is called, Node.js assumes data will be streamed, 3307and sends the new data separately. That is, the response is buffered up to the 3308first chunk of the body. 3309 3310Returns `true` if the entire data was flushed successfully to the kernel 3311buffer. Returns `false` if all or part of the data was queued in user memory. 3312`'drain'` will be emitted when the buffer is free again. 3313 3314#### response.writeContinue() 3315<!-- YAML 3316added: v8.4.0 3317--> 3318 3319Sends a status `100 Continue` to the client, indicating that the request body 3320should be sent. See the [`'checkContinue'`][] event on `Http2Server` and 3321`Http2SecureServer`. 3322 3323#### response.writeHead(statusCode[, statusMessage][, headers]) 3324<!-- YAML 3325added: v8.4.0 3326changes: 3327 - version: v10.17.0 3328 pr-url: https://github.com/nodejs/node/pull/25974 3329 description: Return `this` from `writeHead()` to allow chaining with 3330 `end()`. 3331--> 3332 3333* `statusCode` {number} 3334* `statusMessage` {string} 3335* `headers` {Object} 3336* Returns: {http2.Http2ServerResponse} 3337 3338Sends a response header to the request. The status code is a 3-digit HTTP 3339status code, like `404`. The last argument, `headers`, are the response headers. 3340 3341Returns a reference to the `Http2ServerResponse`, so that calls can be chained. 3342 3343For compatibility with [HTTP/1][], a human-readable `statusMessage` may be 3344passed as the second argument. However, because the `statusMessage` has no 3345meaning within HTTP/2, the argument will have no effect and a process warning 3346will be emitted. 3347 3348```js 3349const body = 'hello world'; 3350response.writeHead(200, { 3351 'Content-Length': Buffer.byteLength(body), 3352 'Content-Type': 'text/plain' }); 3353``` 3354 3355Note that Content-Length is given in bytes not characters. The 3356`Buffer.byteLength()` API may be used to determine the number of bytes in a 3357given encoding. On outbound messages, Node.js does not check if Content-Length 3358and the length of the body being transmitted are equal or not. However, when 3359receiving messages, Node.js will automatically reject messages when the 3360Content-Length does not match the actual payload size. 3361 3362This method may be called at most one time on a message before 3363[`response.end()`][] is called. 3364 3365If [`response.write()`][] or [`response.end()`][] are called before calling 3366this, the implicit/mutable headers will be calculated and call this function. 3367 3368When headers have been set with [`response.setHeader()`][], they will be merged 3369with any headers passed to [`response.writeHead()`][], with the headers passed 3370to [`response.writeHead()`][] given precedence. 3371 3372```js 3373// returns content-type = text/plain 3374const server = http2.createServer((req, res) => { 3375 res.setHeader('Content-Type', 'text/html'); 3376 res.setHeader('X-Foo', 'bar'); 3377 res.writeHead(200, { 'Content-Type': 'text/plain' }); 3378 res.end('ok'); 3379}); 3380``` 3381 3382Attempting to set a header field name or value that contains invalid characters 3383will result in a [`TypeError`][] being thrown. 3384 3385#### response.createPushResponse(headers, callback) 3386<!-- YAML 3387added: v8.4.0 3388--> 3389* `headers` {HTTP/2 Headers Object} An object describing the headers 3390* `callback` {Function} Called once `http2stream.pushStream()` is finished, 3391 or either when the attempt to create the pushed `Http2Stream` has failed or 3392 has been rejected, or the state of `Http2ServerRequest` is closed prior to 3393 calling the `http2stream.pushStream()` method 3394 * `err` {Error} 3395 * `stream` {ServerHttp2Stream} The newly-created `ServerHttp2Stream` object 3396 3397Call [`http2stream.pushStream()`][] with the given headers, and wrap the 3398given [`Http2Stream`] on a newly created `Http2ServerResponse` as the callback 3399parameter if successful. When `Http2ServerRequest` is closed, the callback is 3400called with an error `ERR_HTTP2_INVALID_STREAM`. 3401 3402## Collecting HTTP/2 Performance Metrics 3403 3404The [Performance Observer][] API can be used to collect basic performance 3405metrics for each `Http2Session` and `Http2Stream` instance. 3406 3407```js 3408const { PerformanceObserver } = require('perf_hooks'); 3409 3410const obs = new PerformanceObserver((items) => { 3411 const entry = items.getEntries()[0]; 3412 console.log(entry.entryType); // prints 'http2' 3413 if (entry.name === 'Http2Session') { 3414 // entry contains statistics about the Http2Session 3415 } else if (entry.name === 'Http2Stream') { 3416 // entry contains statistics about the Http2Stream 3417 } 3418}); 3419obs.observe({ entryTypes: ['http2'] }); 3420``` 3421 3422The `entryType` property of the `PerformanceEntry` will be equal to `'http2'`. 3423 3424The `name` property of the `PerformanceEntry` will be equal to either 3425`'Http2Stream'` or `'Http2Session'`. 3426 3427If `name` is equal to `Http2Stream`, the `PerformanceEntry` will contain the 3428following additional properties: 3429 3430* `bytesRead` {number} The number of `DATA` frame bytes received for this 3431 `Http2Stream`. 3432* `bytesWritten` {number} The number of `DATA` frame bytes sent for this 3433 `Http2Stream`. 3434* `id` {number} The identifier of the associated `Http2Stream` 3435* `timeToFirstByte` {number} The number of milliseconds elapsed between the 3436 `PerformanceEntry` `startTime` and the reception of the first `DATA` frame. 3437* `timeToFirstByteSent` {number} The number of milliseconds elapsed between 3438 the `PerformanceEntry` `startTime` and sending of the first `DATA` frame. 3439* `timeToFirstHeader` {number} The number of milliseconds elapsed between the 3440 `PerformanceEntry` `startTime` and the reception of the first header. 3441 3442If `name` is equal to `Http2Session`, the `PerformanceEntry` will contain the 3443following additional properties: 3444 3445* `bytesRead` {number} The number of bytes received for this `Http2Session`. 3446* `bytesWritten` {number} The number of bytes sent for this `Http2Session`. 3447* `framesReceived` {number} The number of HTTP/2 frames received by the 3448 `Http2Session`. 3449* `framesSent` {number} The number of HTTP/2 frames sent by the `Http2Session`. 3450* `maxConcurrentStreams` {number} The maximum number of streams concurrently 3451 open during the lifetime of the `Http2Session`. 3452* `pingRTT` {number} The number of milliseconds elapsed since the transmission 3453 of a `PING` frame and the reception of its acknowledgment. Only present if 3454 a `PING` frame has been sent on the `Http2Session`. 3455* `streamAverageDuration` {number} The average duration (in milliseconds) for 3456 all `Http2Stream` instances. 3457* `streamCount` {number} The number of `Http2Stream` instances processed by 3458 the `Http2Session`. 3459* `type` {string} Either `'server'` or `'client'` to identify the type of 3460 `Http2Session`. 3461 3462[ALPN Protocol ID]: https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids 3463[ALPN negotiation]: #http2_alpn_negotiation 3464[Compatibility API]: #http2_compatibility_api 3465[HTTP/1]: http.html 3466[HTTP/2 Headers Object]: #http2_headers_object 3467[HTTP/2 Settings Object]: #http2_settings_object 3468[HTTP/2 Unencrypted]: https://http2.github.io/faq/#does-http2-require-encryption 3469[HTTP/2]: https://tools.ietf.org/html/rfc7540 3470[HTTPS]: https.html 3471[Performance Observer]: perf_hooks.html 3472[RFC 7838]: https://tools.ietf.org/html/rfc7838 3473[RFC 8336]: https://tools.ietf.org/html/rfc8336 3474[RFC 8441]: https://tools.ietf.org/html/rfc8441 3475[Readable Stream]: stream.html#stream_class_stream_readable 3476[Stream]: stream.html#stream_stream 3477[Using `options.selectPadding()`]: #http2_using_options_selectpadding 3478[`'checkContinue'`]: #http2_event_checkcontinue 3479[`'request'`]: #http2_event_request 3480[`'unknownProtocol'`]: #http2_event_unknownprotocol 3481[`ClientHttp2Stream`]: #http2_class_clienthttp2stream 3482[`Duplex`]: stream.html#stream_class_stream_duplex 3483[`Http2ServerRequest`]: #http2_class_http2_http2serverrequest 3484[`Http2Session` and Sockets]: #http2_http2session_and_sockets 3485[`Http2Stream`]: #http2_class_http2stream 3486[`ServerHttp2Stream`]: #http2_class_serverhttp2stream 3487[`TypeError`]: errors.html#errors_class_typeerror 3488[`http2.SecureServer`]: #http2_class_http2secureserver 3489[`http2.Server`]: #http2_class_http2server 3490[`http2.createSecureServer()`]: #http2_http2_createsecureserver_options_onrequesthandler 3491[`http2.createServer()`]: #http2_http2_createserver_options_onrequesthandler 3492[`http2session.close()`]: #http2_http2session_close_callback 3493[`http2stream.pushStream()`]: #http2_http2stream_pushstream_headers_options_callback 3494[`net.Server.close()`]: net.html#net_server_close_callback 3495[`net.Socket.bufferSize`]: net.html#net_socket_buffersize 3496[`net.Socket.prototype.ref()`]: net.html#net_socket_ref 3497[`net.Socket.prototype.unref()`]: net.html#net_socket_unref 3498[`net.Socket`]: net.html#net_class_net_socket 3499[`net.connect()`]: net.html#net_net_connect 3500[`request.socket.getPeerCertificate()`]: tls.html#tls_tlssocket_getpeercertificate_detailed 3501[`response.end()`]: #http2_response_end_data_encoding_callback 3502[`response.setHeader()`]: #http2_response_setheader_name_value 3503[`response.socket`]: #http2_response_socket 3504[`response.write()`]: #http2_response_write_chunk_encoding_callback 3505[`response.write(data, encoding)`]: http.html#http_response_write_chunk_encoding_callback 3506[`response.writeContinue()`]: #http2_response_writecontinue 3507[`response.writeHead()`]: #http2_response_writehead_statuscode_statusmessage_headers 3508[`tls.Server.close()`]: tls.html#tls_server_close_callback 3509[`tls.TLSSocket`]: tls.html#tls_class_tls_tlssocket 3510[`tls.connect()`]: tls.html#tls_tls_connect_options_callback 3511[`tls.createServer()`]: tls.html#tls_tls_createserver_options_secureconnectionlistener 3512[error code]: #error_codes 3513