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