{ "source": "doc/api/http2.md", "modules": [ { "textRaw": "HTTP/2", "name": "http/2", "introduced_in": "v8.4.0", "stability": 1, "stabilityText": "Experimental", "desc": "
The http2
module provides an implementation of the HTTP/2 protocol. It\ncan be accessed using:
const http2 = require('http2');\n
\n",
"modules": [
{
"textRaw": "Core API",
"name": "core_api",
"desc": "The Core API provides a low-level interface designed specifically around\nsupport for HTTP/2 protocol features. It is specifically not designed for\ncompatibility with the existing HTTP/1 module API. However,\nthe Compatibility API is.
\nThe http2
Core API is much more symmetric between client and server than the\nhttp
API. For instance, most events, like error
, connect
and stream
, can\nbe emitted either by client-side code or server-side code.
The following illustrates a simple HTTP/2 server using the Core API.\nSince there are no browsers known that support\nunencrypted HTTP/2, the use of\nhttp2.createSecureServer()
is necessary when communicating\nwith browser clients.
const http2 = require('http2');\nconst fs = require('fs');\n\nconst server = http2.createSecureServer({\n key: fs.readFileSync('localhost-privkey.pem'),\n cert: fs.readFileSync('localhost-cert.pem')\n});\nserver.on('error', (err) => console.error(err));\n\nserver.on('stream', (stream, headers) => {\n // stream is a Duplex\n stream.respond({\n 'content-type': 'text/html',\n ':status': 200\n });\n stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(8443);\n
\nTo generate the certificate and key for this example, run:
\nopenssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \\\n -keyout localhost-privkey.pem -out localhost-cert.pem\n
\n",
"type": "module",
"displayName": "Server-side example"
},
{
"textRaw": "Client-side example",
"name": "client-side_example",
"desc": "The following illustrates an HTTP/2 client:
\nconst http2 = require('http2');\nconst fs = require('fs');\nconst client = http2.connect('https://localhost:8443', {\n ca: fs.readFileSync('localhost-cert.pem')\n});\nclient.on('error', (err) => console.error(err));\n\nconst req = client.request({ ':path': '/' });\n\nreq.on('response', (headers, flags) => {\n for (const name in headers) {\n console.log(`${name}: ${headers[name]}`);\n }\n});\n\nreq.setEncoding('utf8');\nlet data = '';\nreq.on('data', (chunk) => { data += chunk; });\nreq.on('end', () => {\n console.log(`\\n${data}`);\n client.close();\n});\nreq.end();\n
\n",
"type": "module",
"displayName": "Client-side example"
},
{
"textRaw": "Headers Object",
"name": "headers_object",
"desc": "Headers are represented as own-properties on JavaScript objects. The property\nkeys will be serialized to lower-case. Property values should be strings (if\nthey are not they will be coerced to strings) or an Array of strings (in order\nto send more than one value per header field).
\nconst headers = {\n ':status': '200',\n 'content-type': 'text-plain',\n 'ABC': ['has', 'more', 'than', 'one', 'value']\n};\n\nstream.respond(headers);\n
\nHeader objects passed to callback functions will have a null
prototype. This\nmeans that normal JavaScript object methods such as\nObject.prototype.toString()
and Object.prototype.hasOwnProperty()
will\nnot work.
const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream, headers) => {\n console.log(headers[':path']);\n console.log(headers.ABC);\n});\n
\n",
"type": "module",
"displayName": "Headers Object"
},
{
"textRaw": "Settings Object",
"name": "settings_object",
"meta": {
"added": [
"v8.4.0"
],
"changes": [
{
"version": "v9.1.0",
"pr-url": "https://github.com/nodejs/node/pull/16676",
"description": "The `maxHeaderListSize` setting is now strictly enforced."
}
]
},
"desc": "The http2.getDefaultSettings()
, http2.getPackedSettings()
,\nhttp2.createServer()
, http2.createSecureServer()
,\nhttp2session.settings()
, http2session.localSettings
, and\nhttp2session.remoteSettings
APIs either return or receive as input an\nobject that defines configuration settings for an Http2Session
object.\nThese objects are ordinary JavaScript objects containing the following\nproperties.
headerTableSize
{number} Specifies the maximum number of bytes used for\nheader compression. Default: 4,096 octets
. The minimum allowed\nvalue is 0. The maximum allowed value is 232-1.enablePush
{boolean} Specifies true
if HTTP/2 Push Streams are to be\npermitted on the Http2Session
instances.initialWindowSize
{number} Specifies the senders initial window size\nfor stream-level flow control. Default: 65,535 bytes
. The minimum\nallowed value is 0. The maximum allowed value is 232-1.maxFrameSize
{number} Specifies the size of the largest frame payload.\nDefault: 16,384 bytes
. The minimum allowed value is 16,384. The maximum\nallowed value is 224-1.maxConcurrentStreams
{number} Specifies the maximum number of concurrent\nstreams permitted on an Http2Session
. There is no default value which\nimplies, at least theoretically, 231-1 streams may be open\nconcurrently at any given time in an Http2Session
. The minimum value ismaxHeaderListSize
{number} Specifies the maximum size (uncompressed octets)\nof header list that will be accepted. The minimum allowed value is 0. The\nmaximum allowed value is 232-1. Default: 65535.All additional properties on the settings object are ignored.
\n", "type": "module", "displayName": "Settings Object" }, { "textRaw": "Error Handling", "name": "error_handling", "desc": "There are several types of error conditions that may arise when using the\nhttp2
module:
Validation Errors occur when an incorrect argument, option, or setting value is\npassed in. These will always be reported by a synchronous throw
.
State Errors occur when an action is attempted at an incorrect time (for\ninstance, attempting to send data on a stream after it has closed). These will\nbe reported using either a synchronous throw
or via an 'error'
event on\nthe Http2Stream
, Http2Session
or HTTP/2 Server objects, depending on where\nand when the error occurs.
Internal Errors occur when an HTTP/2 session fails unexpectedly. These will be\nreported via an 'error'
event on the Http2Session
or HTTP/2 Server objects.
Protocol Errors occur when various HTTP/2 protocol constraints are violated.\nThese will be reported using either a synchronous throw
or via an 'error'
\nevent on the Http2Stream
, Http2Session
or HTTP/2 Server objects, depending\non where and when the error occurs.
The HTTP/2 implementation applies stricter handling of invalid characters in\nHTTP header names and values than the HTTP/1 implementation.
\nHeader field names are case-insensitive and are transmitted over the wire\nstrictly as lower-case strings. The API provided by Node.js allows header\nnames to be set as mixed-case strings (e.g. Content-Type
) but will convert\nthose to lower-case (e.g. content-type
) upon transmission.
Header field-names must only contain one or more of the following ASCII\ncharacters: a
-z
, A
-Z
, 0
-9
, !
, #
, $
, %
, &
, '
, *
, +
,\n-
, .
, ^
, _
, `
(backtick), |
, and ~
.
Using invalid characters within an HTTP header field name will cause the\nstream to be closed with a protocol error being reported.
\nHeader field values are handled with more leniency but should not contain\nnew-line or carriage return characters and should be limited to US-ASCII\ncharacters, per the requirements of the HTTP specification.
\n", "type": "module", "displayName": "Invalid character handling in header names and values" }, { "textRaw": "Push streams on the client", "name": "push_streams_on_the_client", "desc": "To receive pushed streams on the client, set a listener for the 'stream'
\nevent on the ClientHttp2Session
:
const http2 = require('http2');\n\nconst client = http2.connect('http://localhost');\n\nclient.on('stream', (pushedStream, requestHeaders) => {\n pushedStream.on('push', (responseHeaders) => {\n // process response headers\n });\n pushedStream.on('data', (chunk) => { /* handle pushed data */ });\n});\n\nconst req = client.request({ ':path': '/' });\n
\n",
"type": "module",
"displayName": "Push streams on the client"
},
{
"textRaw": "Supporting the CONNECT method",
"name": "supporting_the_connect_method",
"desc": "The CONNECT
method is used to allow an HTTP/2 server to be used as a proxy\nfor TCP/IP connections.
A simple TCP Server:
\nconst net = require('net');\n\nconst server = net.createServer((socket) => {\n let name = '';\n socket.setEncoding('utf8');\n socket.on('data', (chunk) => name += chunk);\n socket.on('end', () => socket.end(`hello ${name}`));\n});\n\nserver.listen(8000);\n
\nAn HTTP/2 CONNECT proxy:
\nconst http2 = require('http2');\nconst { NGHTTP2_REFUSED_STREAM } = http2.constants;\nconst net = require('net');\nconst { URL } = require('url');\n\nconst proxy = http2.createServer();\nproxy.on('stream', (stream, headers) => {\n if (headers[':method'] !== 'CONNECT') {\n // Only accept CONNECT requests\n stream.close(NGHTTP2_REFUSED_STREAM);\n return;\n }\n const auth = new URL(`tcp://${headers[':authority']}`);\n // It's a very good idea to verify that hostname and port are\n // things this proxy should be connecting to.\n const socket = net.connect(auth.port, auth.hostname, () => {\n stream.respond();\n socket.pipe(stream);\n stream.pipe(socket);\n });\n socket.on('error', (error) => {\n stream.close(http2.constants.NGHTTP2_CONNECT_ERROR);\n });\n});\n\nproxy.listen(8001);\n
\nAn HTTP/2 CONNECT client:
\nconst http2 = require('http2');\n\nconst client = http2.connect('http://localhost:8001');\n\n// Must not specify the ':path' and ':scheme' headers\n// for CONNECT requests or an error will be thrown.\nconst req = client.request({\n ':method': 'CONNECT',\n ':authority': `localhost:${port}`\n});\n\nreq.on('response', (headers) => {\n console.log(headers[http2.constants.HTTP2_HEADER_STATUS]);\n});\nlet data = '';\nreq.setEncoding('utf8');\nreq.on('data', (chunk) => data += chunk);\nreq.on('end', () => {\n console.log(`The server says: ${data}`);\n client.close();\n});\nreq.end('Jane');\n
\n",
"type": "module",
"displayName": "Supporting the CONNECT method"
}
],
"classes": [
{
"textRaw": "Class: Http2Session",
"type": "class",
"name": "Http2Session",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "Instances of the http2.Http2Session
class represent an active communications\nsession between an HTTP/2 client and server. Instances of this class are not\nintended to be constructed directly by user code.
Each Http2Session
instance will exhibit slightly different behaviors\ndepending on whether it is operating as a server or a client. The\nhttp2session.type
property can be used to determine the mode in which an\nHttp2Session
is operating. On the server side, user code should rarely\nhave occasion to work with the Http2Session
object directly, with most\nactions typically taken through interactions with either the Http2Server
or\nHttp2Stream
objects.
Every Http2Session
instance is associated with exactly one net.Socket
or\ntls.TLSSocket
when it is created. When either the Socket
or the\nHttp2Session
are destroyed, both will be destroyed.
Because the of the specific serialization and processing requirements imposed\nby the HTTP/2 protocol, it is not recommended for user code to read data from\nor write data to a Socket
instance bound to a Http2Session
. Doing so can\nput the HTTP/2 session into an indeterminate state causing the session and\nthe socket to become unusable.
Once a Socket
has been bound to an Http2Session
, user code should rely\nsolely on the API of the Http2Session
.
The 'close'
event is emitted once the Http2Session
has been destroyed.
The 'connect'
event is emitted once the Http2Session
has been successfully\nconnected to the remote peer and communication may begin.
User code will typically not listen for this event directly.
\n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "The 'error'
event is emitted when an error occurs during the processing of\nan Http2Session
.
The 'frameError'
event is emitted when an error occurs while attempting to\nsend a frame on the session. If the frame that could not be sent is associated\nwith a specific Http2Stream
, an attempt to emit 'frameError'
event on the\nHttp2Stream
is made.
When invoked, the handler function will receive three arguments:
\nIf the 'frameError'
event is associated with a stream, the stream will be\nclosed and destroyed immediately following the 'frameError'
event. If the\nevent is not associated with a stream, the Http2Session
will be shut down\nimmediately following the 'frameError'
event.
The 'goaway'
event is emitted when a GOAWAY frame is received. When invoked,\nthe handler function will receive three arguments:
errorCode
{number} The HTTP/2 error code specified in the GOAWAY frame.lastStreamID
{number} The ID of the last stream the remote peer successfully\nprocessed (or 0
if no ID is specified).opaqueData
{Buffer} If additional opaque data was included in the GOAWAY\nframe, a Buffer
instance will be passed containing that data.The Http2Session
instance will be shut down automatically when the 'goaway'
\nevent is emitted.
The 'localSettings'
event is emitted when an acknowledgment SETTINGS frame\nhas been received. When invoked, the handler function will receive a copy of\nthe local settings.
When using http2session.settings()
to submit new settings, the modified\nsettings do not take effect until the 'localSettings'
event is emitted.
session.settings({ enablePush: false });\n\nsession.on('localSettings', (settings) => {\n /** use the new settings **/\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'remoteSettings'",
"type": "event",
"name": "remoteSettings",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "The 'remoteSettings'
event is emitted when a new SETTINGS frame is received\nfrom the connected peer. When invoked, the handler function will receive a copy\nof the remote settings.
session.on('remoteSettings', (settings) => {\n /** use the new settings **/\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'stream'",
"type": "event",
"name": "stream",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "The 'stream'
event is emitted when a new Http2Stream
is created. When\ninvoked, the handler function will receive a reference to the Http2Stream
\nobject, a HTTP/2 Headers Object, and numeric flags associated with the\ncreation of the stream.
const http2 = require('http2');\nsession.on('stream', (stream, headers, flags) => {\n const method = headers[':method'];\n const path = headers[':path'];\n // ...\n stream.respond({\n ':status': 200,\n 'content-type': 'text/plain'\n });\n stream.write('hello ');\n stream.end('world');\n});\n
\nOn the server side, user code will typically not listen for this event directly,\nand would instead register a handler for the 'stream'
event emitted by the\nnet.Server
or tls.Server
instances returned by http2.createServer()
and\nhttp2.createSecureServer()
, respectively, as in the example below:
const http2 = require('http2');\n\n// Create an unencrypted HTTP/2 server\nconst server = http2.createServer();\n\nserver.on('stream', (stream, headers) => {\n stream.respond({\n 'content-type': 'text/html',\n ':status': 200\n });\n stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(80);\n
\n",
"params": []
},
{
"textRaw": "Event: 'timeout'",
"type": "event",
"name": "timeout",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "After the http2session.setTimeout()
method is used to set the timeout period\nfor this Http2Session
, the 'timeout'
event is emitted if there is no\nactivity on the Http2Session
after the configured number of milliseconds.
session.setTimeout(2000);\nsession.on('timeout', () => { /** .. **/ });\n
\n",
"params": []
}
],
"properties": [
{
"textRaw": "`alpnProtocol` Value: {string|undefined} ",
"name": "alpnProtocol",
"meta": {
"added": [
"v9.4.0"
],
"changes": []
},
"desc": "Value will be undefined
if the Http2Session
is not yet connected to a\nsocket, h2c
if the Http2Session
is not connected to a TLSSocket
, or\nwill return the value of the connected TLSSocket
's own alpnProtocol
\nproperty.
Will be true
if this Http2Session
instance has been closed, otherwise\nfalse
.
Will be true
if this Http2Session
instance has been destroyed and must no\nlonger be used, otherwise false
.
Value is undefined
if the Http2Session
session socket has not yet been\nconnected, true
if the Http2Session
is connected with a TLSSocket
,\nand false
if the Http2Session
is connected to any other kind of socket\nor stream.
A prototype-less object describing the current local settings of this\nHttp2Session
. The local settings are local to this Http2Session
instance.
If the Http2Session
is connected to a TLSSocket
, the originSet
property\nwill return an Array of origins for which the Http2Session
may be\nconsidered authoritative.
Indicates whether or not the Http2Session
is currently waiting for an\nacknowledgment for a sent SETTINGS frame. Will be true
after calling the\nhttp2session.settings()
method. Will be false
once all sent SETTINGS\nframes have been acknowledged.
A prototype-less object describing the current remote settings of this\nHttp2Session
. The remote settings are set by the connected HTTP/2 peer.
Returns a Proxy object that acts as a net.Socket
(or tls.TLSSocket
) but\nlimits available methods to ones safe to use with HTTP/2.
destroy
, emit
, end
, pause
, read
, resume
, and write
will throw\nan error with code ERR_HTTP2_NO_SOCKET_MANIPULATION
. See\nHttp2Session and Sockets for more information.
setTimeout
method will be called on this Http2Session
.
All other interactions will be routed directly to the socket.
\n", "shortDesc": "Value: {net.Socket|tls.TLSSocket}" }, { "textRaw": "http2session.state", "name": "state", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "Provides miscellaneous information about the current state of the\nHttp2Session
.
effectiveLocalWindowSize
{number} The current local (receive)\nflow control window size for the Http2Session
.effectiveRecvDataLength
{number} The current number of bytes\nthat have been received since the last flow control WINDOW_UPDATE
.nextStreamID
{number} The numeric identifier to be used the\nnext time a new Http2Stream
is created by this Http2Session
.localWindowSize
{number} The number of bytes that the remote peer can\nsend without receiving a WINDOW_UPDATE
.lastProcStreamID
{number} The numeric id of the Http2Stream
\nfor which a HEADERS
or DATA
frame was most recently received.remoteWindowSize
{number} The number of bytes that this Http2Session
\nmay send without receiving a WINDOW_UPDATE
.outboundQueueSize
{number} The number of frames currently within the\noutbound queue for this Http2Session
.deflateDynamicTableSize
{number} The current size in bytes of the\noutbound header compression state table.inflateDynamicTableSize
{number} The current size in bytes of the\ninbound header compression state table.An object describing the current status of this Http2Session
.
The http2session.type
will be equal to\nhttp2.constants.NGHTTP2_SESSION_SERVER
if this Http2Session
instance is a\nserver, and http2.constants.NGHTTP2_SESSION_CLIENT
if the instance is a\nclient.
Gracefully closes the Http2Session
, allowing any existing streams to\ncomplete on their own and preventing new Http2Stream
instances from being\ncreated. Once closed, http2session.destroy()
might be called if there\nare no open Http2Stream
instances.
If specified, the callback
function is registered as a handler for the\n'close'
event.
Immediately terminates the Http2Session
and the associated net.Socket
or\ntls.TLSSocket
.
Once destroyed, the Http2Session
will emit the 'close'
event. If error
\nis not undefined, an 'error'
event will be emitted immediately after the\n'close'
event.
If there are any remaining open Http2Streams
associated with the\nHttp2Session
, those will also be destroyed.
Transmits a GOAWAY
frame to the connected peer without shutting down the\nHttp2Session
.
Sends a PING
frame to the connected HTTP/2 peer. A callback
function must\nbe provided. The method will return true
if the PING
was sent, false
\notherwise.
The maximum number of outstanding (unacknowledged) pings is determined by the\nmaxOutstandingPings
configuration option. The default maximum is 10.
If provided, the payload
must be a Buffer
, TypedArray
, or DataView
\ncontaining 8 bytes of data that will be transmitted with the PING
and\nreturned with the ping acknowledgment.
The callback will be invoked with three arguments: an error argument that will\nbe null
if the PING
was successfully acknowledged, a duration
argument\nthat reports the number of milliseconds elapsed since the ping was sent and the\nacknowledgment was received, and a Buffer
containing the 8-byte PING
\npayload.
session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => {\n if (!err) {\n console.log(`Ping acknowledged in ${duration} milliseconds`);\n console.log(`With payload '${payload.toString()}`);\n }\n});\n
\nIf the payload
argument is not specified, the default payload will be the\n64-bit timestamp (little endian) marking the start of the PING
duration.
Calls ref()
on this Http2Session
\ninstance's underlying net.Socket
.
Used to set a callback function that is called when there is no activity on\nthe Http2Session
after msecs
milliseconds. The given callback
is\nregistered as a listener on the 'timeout'
event.
Updates the current local settings for this Http2Session
and sends a new\nSETTINGS
frame to the connected HTTP/2 peer.
Once called, the http2session.pendingSettingsAck
property will be true
\nwhile the session is waiting for the remote peer to acknowledge the new\nsettings.
The new settings will not become effective until the SETTINGS acknowledgment is\nreceived and the 'localSettings'
event is emitted. It is possible to send\nmultiple SETTINGS frames while acknowledgment is still pending.
Calls unref()
on this Http2Session
\ninstance's underlying net.Socket
.
Submits an ALTSVC
frame (as defined by RFC 7838) to the connected client.
const http2 = require('http2');\n\nconst server = http2.createServer();\nserver.on('session', (session) => {\n // Set altsvc for origin https://example.org:80\n session.altsvc('h2=":8000"', 'https://example.org:80');\n});\n\nserver.on('stream', (stream) => {\n // Set altsvc for a specific stream\n stream.session.altsvc('h2=":8000"', stream.id);\n});\n
\nSending an ALTSVC
frame with a specific stream ID indicates that the alternate\nservice is associated with the origin of the given Http2Stream
.
The alt
and origin string must contain only ASCII bytes and are\nstrictly interpreted as a sequence of ASCII bytes. The special value 'clear'
\nmay be passed to clear any previously set alternative service for a given\ndomain.
When a string is passed for the originOrStream
argument, it will be parsed as\na URL and the origin will be derived. For instance, the origin for the\nHTTP URL 'https://example.org/foo/bar'
is the ASCII string\n'https://example.org'
. An error will be thrown if either the given string\ncannot be parsed as a URL or if a valid origin cannot be derived.
A URL
object, or any object with an origin
property, may be passed as\noriginOrStream
, in which case the value of the origin
property will be\nused. The value of the origin
property must be a properly serialized\nASCII origin.
The format of the alt
parameter is strictly defined by RFC 7838 as an\nASCII string containing a comma-delimited list of "alternative" protocols\nassociated with a specific host and port.
For example, the value 'h2="example.org:81"'
indicates that the HTTP/2\nprotocol is available on the host 'example.org'
on TCP/IP port 81. The\nhost and port must be contained within the quote ("
) characters.
Multiple alternatives may be specified, for instance: 'h2="example.org:81",\nh2=":82"'
The protocol identifier ('h2'
in the examples) may be any valid\nALPN Protocol ID.
The syntax of these values is not validated by the Node.js implementation and\nare passed through as provided by the user or received from the peer.
\n", "type": "module", "displayName": "Specifying alternative services" } ] }, { "textRaw": "Class: ClientHttp2Session", "type": "class", "name": "ClientHttp2Session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "events": [ { "textRaw": "Event: 'altsvc'", "type": "event", "name": "altsvc", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "params": [], "desc": "The 'altsvc'
event is emitted whenever an ALTSVC
frame is received by\nthe client. The event is emitted with the ALTSVC
value, origin, and stream\nID. If no origin
is provided in the ALTSVC
frame, origin
will\nbe an empty string.
const http2 = require('http2');\nconst client = http2.connect('https://example.org');\n\nclient.on('altsvc', (alt, origin, streamId) => {\n console.log(alt);\n console.log(origin);\n console.log(streamId);\n});\n
\n"
}
],
"methods": [
{
"textRaw": "clienthttp2session.request(headers[, options])",
"type": "method",
"name": "request",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {ClientHttp2Stream} ",
"name": "return",
"type": "ClientHttp2Stream"
},
"params": [
{
"textRaw": "`headers` {HTTP/2 Headers Object} ",
"name": "headers",
"type": "HTTP/2 Headers Object"
},
{
"textRaw": "`options` {Object} ",
"options": [
{
"textRaw": "`endStream` {boolean} `true` if the `Http2Stream` *writable* side should be closed initially, such as when sending a `GET` request that should not expect a payload body. ",
"name": "endStream",
"type": "boolean",
"desc": "`true` if the `Http2Stream` *writable* side should be closed initially, such as when sending a `GET` request that should not expect a payload body."
},
{
"textRaw": "`exclusive` {boolean} When `true` and `parent` identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of the newly created stream. **Default:** `false` ",
"name": "exclusive",
"type": "boolean",
"desc": "When `true` and `parent` identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of the newly created stream. **Default:** `false`"
},
{
"textRaw": "`parent` {number} Specifies the numeric identifier of a stream the newly created stream is dependent on. ",
"name": "parent",
"type": "number",
"desc": "Specifies the numeric identifier of a stream the newly created stream is dependent on."
},
{
"textRaw": "`weight` {number} Specifies the relative dependency of a stream in relation to other streams with the same `parent`. The value is a number between `1` and `256` (inclusive). ",
"name": "weight",
"type": "number",
"desc": "Specifies the relative dependency of a stream in relation to other streams with the same `parent`. The value is a number between `1` and `256` (inclusive)."
},
{
"textRaw": "`getTrailers` {Function} Callback function invoked to collect trailer headers. ",
"name": "getTrailers",
"type": "Function",
"desc": "Callback function invoked to collect trailer headers."
}
],
"name": "options",
"type": "Object",
"optional": true
}
]
},
{
"params": [
{
"name": "headers"
},
{
"name": "options",
"optional": true
}
]
}
],
"desc": "For HTTP/2 Client Http2Session
instances only, the http2session.request()
\ncreates and returns an Http2Stream
instance that can be used to send an\nHTTP/2 request to the connected server.
This method is only available if http2session.type
is equal to\nhttp2.constants.NGHTTP2_SESSION_CLIENT
.
const http2 = require('http2');\nconst clientSession = http2.connect('https://localhost:1234');\nconst {\n HTTP2_HEADER_PATH,\n HTTP2_HEADER_STATUS\n} = http2.constants;\n\nconst req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' });\nreq.on('response', (headers) => {\n console.log(headers[HTTP2_HEADER_STATUS]);\n req.on('data', (chunk) => { /** .. **/ });\n req.on('end', () => { /** .. **/ });\n});\n
\nWhen set, the options.getTrailers()
function is called immediately after\nqueuing the last chunk of payload data to be sent. The callback is passed a\nsingle object (with a null
prototype) that the listener may use to specify\nthe trailing header fields to send to the peer.
The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header\nfields (e.g. ':method'
, ':path'
, etc). An 'error'
event will be emitted\nif the getTrailers
callback attempts to set such header fields.
The :method
and :path
pseudo-headers are not specified within headers
,\nthey respectively default to:
:method
= 'GET'
:path
= /
Each instance of the Http2Stream
class represents a bidirectional HTTP/2\ncommunications stream over an Http2Session
instance. Any single Http2Session
\nmay have up to 231-1 Http2Stream
instances over its lifetime.
User code will not construct Http2Stream
instances directly. Rather, these\nare created, managed, and provided to user code through the Http2Session
\ninstance. On the server, Http2Stream
instances are created either in response\nto an incoming HTTP request (and handed off to user code via the 'stream'
\nevent), or in response to a call to the http2stream.pushStream()
method.\nOn the client, Http2Stream
instances are created and returned when either the\nhttp2session.request()
method is called, or in response to an incoming\n'push'
event.
The Http2Stream
class is a base for the ServerHttp2Stream
and\nClientHttp2Stream
classes, each of which is used specifically by either\nthe Server or Client side, respectively.
All Http2Stream
instances are Duplex
streams. The Writable
side of the\nDuplex
is used to send data to the connected peer, while the Readable
side\nis used to receive data sent by the connected peer.
On the server side, instances of ServerHttp2Stream
are created either\nwhen:
HEADERS
frame with a previously unused stream ID is received;http2stream.pushStream()
method is called.On the client side, instances of ClientHttp2Stream
are created when the\nhttp2session.request()
method is called.
On the client, the Http2Stream
instance returned by http2session.request()
\nmay not be immediately ready for use if the parent Http2Session
has not yet\nbeen fully established. In such cases, operations called on the Http2Stream
\nwill be buffered until the 'ready'
event is emitted. User code should rarely,\nif ever, need to handle the 'ready'
event directly. The ready status of an\nHttp2Stream
can be determined by checking the value of http2stream.id
. If\nthe value is undefined
, the stream is not yet ready for use.
All Http2Stream
instances are destroyed either when:
RST_STREAM
frame for the stream is received by the connected peer.http2stream.close()
method is called.http2stream.destroy()
or http2session.destroy()
methods are called.When an Http2Stream
instance is destroyed, an attempt will be made to send an\nRST_STREAM
frame will be sent to the connected peer.
When the Http2Stream
instance is destroyed, the 'close'
event will\nbe emitted. Because Http2Stream
is an instance of stream.Duplex
, the\n'end'
event will also be emitted if the stream data is currently flowing.\nThe 'error'
event may also be emitted if http2stream.destroy()
was called\nwith an Error
passed as the first argument.
After the Http2Stream
has been destroyed, the http2stream.destroyed
\nproperty will be true
and the http2stream.rstCode
property will specify the\nRST_STREAM
error code. The Http2Stream
instance is no longer usable once\ndestroyed.
The 'aborted'
event is emitted whenever a Http2Stream
instance is\nabnormally aborted in mid-communication.
The 'aborted'
event will only be emitted if the Http2Stream
writable side\nhas not been ended.
The 'close'
event is emitted when the Http2Stream
is destroyed. Once\nthis event is emitted, the Http2Stream
instance is no longer usable.
The listener callback is passed a single argument specifying the HTTP/2 error\ncode specified when closing the stream. If the code is any value other than\nNGHTTP2_NO_ERROR
(0
), an 'error'
event will also be emitted.
The 'error'
event is emitted when an error occurs during the processing of\nan Http2Stream
.
The 'frameError'
event is emitted when an error occurs while attempting to\nsend a frame. When invoked, the handler function will receive an integer\nargument identifying the frame type, and an integer argument identifying the\nerror code. The Http2Stream
instance will be destroyed immediately after the\n'frameError'
event is emitted.
The 'timeout'
event is emitted after no activity is received for this\n'Http2Stream'
within the number of milliseconds set using\nhttp2stream.setTimeout()
.
The 'trailers'
event is emitted when a block of headers associated with\ntrailing header fields is received. The listener callback is passed the\nHTTP/2 Headers Object and flags associated with the headers.
stream.on('trailers', (headers, flags) => {\n console.log(headers);\n});\n
\n",
"params": []
}
],
"properties": [
{
"textRaw": "`aborted` Value: {boolean} ",
"name": "aborted",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "Set to true
if the Http2Stream
instance was aborted abnormally. When set,\nthe 'aborted'
event will have been emitted.
Set to true
if the Http2Stream
instance has been closed.
Set to true
if the Http2Stream
instance has been destroyed and is no longer\nusable.
Set to true
if the Http2Stream
instance has not yet been assigned a\nnumeric stream identifier.
Set to the RST_STREAM
error code reported when the Http2Stream
is\ndestroyed after either receiving an RST_STREAM
frame from the connected peer,\ncalling http2stream.close()
, or http2stream.destroy()
. Will be\nundefined
if the Http2Stream
has not been closed.
An object containing the outbound headers sent for this Http2Stream
.
An array of objects containing the outbound informational (additional) headers\nsent for this Http2Stream
.
An object containing the outbound trailers sent for this this HttpStream
.
A reference to the Http2Session
instance that owns this Http2Stream
. The\nvalue will be undefined
after the Http2Stream
instance is destroyed.
Provides miscellaneous information about the current state of the\nHttp2Stream
.
localWindowSize
{number} The number of bytes the connected peer may send\nfor this Http2Stream
without receiving a WINDOW_UPDATE
.state
{number} A flag indicating the low-level current state of the\nHttp2Stream
as determined by nghttp2.localClose
{number} true
if this Http2Stream
has been closed locally.remoteClose
{number} true
if this Http2Stream
has been closed\nremotely.sumDependencyWeight
{number} The sum weight of all Http2Stream
\ninstances that depend on this Http2Stream
as specified using\nPRIORITY
frames.weight
{number} The priority weight of this Http2Stream
.A current state of this Http2Stream
.
Closes the Http2Stream
instance by sending an RST_STREAM
frame to the\nconnected HTTP/2 peer.
Updates the priority for this Http2Stream
instance.
const http2 = require('http2');\nconst client = http2.connect('http://example.org:8000');\nconst { NGHTTP2_CANCEL } = http2.constants;\nconst req = client.request({ ':path': '/' });\n\n// Cancel the stream if there's no activity after 5 seconds\nreq.setTimeout(5000, () => req.close(NGHTTP2_CANCEL));\n
\n"
}
]
},
{
"textRaw": "Class: ClientHttp2Stream",
"type": "class",
"name": "ClientHttp2Stream",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "The ClientHttp2Stream
class is an extension of Http2Stream
that is\nused exclusively on HTTP/2 Clients. Http2Stream
instances on the client\nprovide events such as 'response'
and 'push'
that are only relevant on\nthe client.
Emitted when the server sends a 100 Continue
status, usually because\nthe request contained Expect: 100-continue
. This is an instruction that\nthe client should send the request body.
The 'headers'
event is emitted when an additional block of headers is received\nfor a stream, such as when a block of 1xx
informational headers is received.\nThe listener callback is passed the HTTP/2 Headers Object and flags\nassociated with the headers.
stream.on('headers', (headers, flags) => {\n console.log(headers);\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'push'",
"type": "event",
"name": "push",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "The 'push'
event is emitted when response headers for a Server Push stream\nare received. The listener callback is passed the HTTP/2 Headers Object and\nflags associated with the headers.
stream.on('push', (headers, flags) => {\n console.log(headers);\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'response'",
"type": "event",
"name": "response",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "The 'response'
event is emitted when a response HEADERS
frame has been\nreceived for this stream from the connected HTTP/2 server. The listener is\ninvoked with two arguments: an Object containing the received\nHTTP/2 Headers Object, and flags associated with the headers.
const http2 = require('http2');\nconst client = http2.connect('https://localhost');\nconst req = client.request({ ':path': '/' });\nreq.on('response', (headers, flags) => {\n console.log(headers[':status']);\n});\n
\n",
"params": []
}
]
},
{
"textRaw": "Class: ServerHttp2Stream",
"type": "class",
"name": "ServerHttp2Stream",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "The ServerHttp2Stream
class is an extension of Http2Stream
that is\nused exclusively on HTTP/2 Servers. Http2Stream
instances on the server\nprovide additional methods such as http2stream.pushStream()
and\nhttp2stream.respond()
that are only relevant on the server.
Sends an additional informational HEADERS
frame to the connected HTTP/2 peer.
Initiates a push stream. The callback is invoked with the new Http2Stream
\ninstance created for the push stream passed as the second argument, or an\nError
passed as the first argument.
const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n stream.respond({ ':status': 200 });\n stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => {\n if (err) throw err;\n pushStream.respond({ ':status': 200 });\n pushStream.end('some pushed data');\n });\n stream.end('some data');\n});\n
\nSetting the weight of a push stream is not allowed in the HEADERS
frame. Pass\na weight
value to http2stream.priority
with the silent
option set to\ntrue
to enable server-side bandwidth balancing between concurrent streams.
const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n stream.respond({ ':status': 200 });\n stream.end('some data');\n});\n
\nWhen set, the options.getTrailers()
function is called immediately after\nqueuing the last chunk of payload data to be sent. The callback is passed a\nsingle object (with a null
prototype) that the listener may use to specify\nthe trailing header fields to send to the peer.
const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n stream.respond({ ':status': 200 }, {\n getTrailers(trailers) {\n trailers.ABC = 'some value to send';\n }\n });\n stream.end('some data');\n});\n
\nThe HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header\nfields (e.g. ':status'
, ':path'
, etc). An 'error'
event will be emitted\nif the getTrailers
callback attempts to set such header fields.
Initiates a response whose data is read from the given file descriptor. No\nvalidation is performed on the given file descriptor. If an error occurs while\nattempting to read data using the file descriptor, the Http2Stream
will be\nclosed using an RST_STREAM
frame using the standard INTERNAL_ERROR
code.
When used, the Http2Stream
object's Duplex interface will be closed\nautomatically.
const http2 = require('http2');\nconst fs = require('fs');\n\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n const fd = fs.openSync('/some/file', 'r');\n\n const stat = fs.fstatSync(fd);\n const headers = {\n 'content-length': stat.size,\n 'last-modified': stat.mtime.toUTCString(),\n 'content-type': 'text/plain'\n };\n stream.respondWithFD(fd, headers);\n stream.on('close', () => fs.closeSync(fd));\n});\n
\nThe optional options.statCheck
function may be specified to give user code\nan opportunity to set additional content headers based on the fs.Stat
details\nof the given fd. If the statCheck
function is provided, the\nhttp2stream.respondWithFD()
method will perform an fs.fstat()
call to\ncollect details on the provided file descriptor.
The offset
and length
options may be used to limit the response to a\nspecific range subset. This can be used, for instance, to support HTTP Range\nrequests.
The file descriptor is not closed when the stream is closed, so it will need\nto be closed manually once it is no longer needed.\nNote that using the same file descriptor concurrently for multiple streams\nis not supported and may result in data loss. Re-using a file descriptor\nafter a stream has finished is supported.
\nWhen set, the options.getTrailers()
function is called immediately after\nqueuing the last chunk of payload data to be sent. The callback is passed a\nsingle object (with a null
prototype) that the listener may use to specify\nthe trailing header fields to send to the peer.
const http2 = require('http2');\nconst fs = require('fs');\n\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n const fd = fs.openSync('/some/file', 'r');\n\n const stat = fs.fstatSync(fd);\n const headers = {\n 'content-length': stat.size,\n 'last-modified': stat.mtime.toUTCString(),\n 'content-type': 'text/plain'\n };\n stream.respondWithFD(fd, headers, {\n getTrailers(trailers) {\n trailers.ABC = 'some value to send';\n }\n });\n\n stream.on('close', () => fs.closeSync(fd));\n});\n
\nThe HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header\nfields (e.g. ':status'
, ':path'
, etc). An 'error'
event will be emitted\nif the getTrailers
callback attempts to set such header fields.
Sends a regular file as the response. The path
must specify a regular file\nor an 'error'
event will be emitted on the Http2Stream
object.
When used, the Http2Stream
object's Duplex interface will be closed\nautomatically.
The optional options.statCheck
function may be specified to give user code\nan opportunity to set additional content headers based on the fs.Stat
details\nof the given file:
If an error occurs while attempting to read the file data, the Http2Stream
\nwill be closed using an RST_STREAM
frame using the standard INTERNAL_ERROR
\ncode. If the onError
callback is defined, then it will be called. Otherwise\nthe stream will be destroyed.
Example using a file path:
\nconst http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n function statCheck(stat, headers) {\n headers['last-modified'] = stat.mtime.toUTCString();\n }\n\n function onError(err) {\n if (err.code === 'ENOENT') {\n stream.respond({ ':status': 404 });\n } else {\n stream.respond({ ':status': 500 });\n }\n stream.end();\n }\n\n stream.respondWithFile('/some/file',\n { 'content-type': 'text/plain' },\n { statCheck, onError });\n});\n
\nThe options.statCheck
function may also be used to cancel the send operation\nby returning false
. For instance, a conditional request may check the stat\nresults to determine if the file has been modified to return an appropriate\n304
response:
const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n function statCheck(stat, headers) {\n // Check the stat here...\n stream.respond({ ':status': 304 });\n return false; // Cancel the send operation\n }\n stream.respondWithFile('/some/file',\n { 'content-type': 'text/plain' },\n { statCheck });\n});\n
\nThe content-length
header field will be automatically set.
The offset
and length
options may be used to limit the response to a\nspecific range subset. This can be used, for instance, to support HTTP Range\nrequests.
The options.onError
function may also be used to handle all the errors\nthat could happen before the delivery of the file is initiated. The\ndefault behavior is to destroy the stream.
When set, the options.getTrailers()
function is called immediately after\nqueuing the last chunk of payload data to be sent. The callback is passed a\nsingle object (with a null
prototype) that the listener may use to specify\nthe trailing header fields to send to the peer.
const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n function getTrailers(trailers) {\n trailers.ABC = 'some value to send';\n }\n stream.respondWithFile('/some/file',\n { 'content-type': 'text/plain' },\n { getTrailers });\n});\n
\nThe HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header\nfields (e.g. ':status'
, ':path'
, etc). An 'error'
event will be emitted\nif the getTrailers
callback attempts to set such header fields.
Boolean (read-only). True if headers were sent, false otherwise.
\n", "shortDesc": "Value: {boolean}" }, { "textRaw": "`pushAllowed` Value: {boolean} ", "name": "pushAllowed", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "Read-only property mapped to the SETTINGS_ENABLE_PUSH
flag of the remote\nclient's most recent SETTINGS
frame. Will be true
if the remote peer\naccepts push streams, false
otherwise. Settings are the same for every\nHttp2Stream
in the same Http2Session
.
In Http2Server
, there are no 'clientError'
events as there are in\nHTTP1. However, there are 'sessionError'
, and 'streamError'
events for\nerrors emitted on the socket, or from Http2Session
or Http2Stream
instances.
If a 'request'
listener is registered or http2.createServer()
is\nsupplied a callback function, the 'checkContinue'
event is emitted each time\na request with an HTTP Expect: 100-continue
is received. If this event is\nnot listened for, the server will automatically respond with a status\n100 Continue
as appropriate.
Handling this event involves calling response.writeContinue()
if the \nclient should continue to send the request body, or generating an appropriate \nHTTP response (e.g. 400 Bad Request) if the client should not continue to send \nthe request body.
Note that when this event is emitted and handled, the 'request'
event will\nnot be emitted.
Emitted each time there is a request. Note that there may be multiple requests\nper session. See the Compatibility API.
\n" }, { "textRaw": "Event: 'session'", "type": "event", "name": "session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "The 'session'
event is emitted when a new Http2Session
is created by the\nHttp2Server
.
The 'sessionError'
event is emitted when an 'error'
event is emitted by\nan Http2Session
object associated with the Http2Server
.
If a ServerHttp2Stream
emits an 'error'
event, it will be forwarded here.\nThe stream will already be destroyed when this event is triggered.
The 'stream'
event is emitted when a 'stream'
event has been emitted by\nan Http2Session
associated with the server.
const http2 = require('http2');\nconst {\n HTTP2_HEADER_METHOD,\n HTTP2_HEADER_PATH,\n HTTP2_HEADER_STATUS,\n HTTP2_HEADER_CONTENT_TYPE\n} = http2.constants;\n\nconst server = http2.createServer();\nserver.on('stream', (stream, headers, flags) => {\n const method = headers[HTTP2_HEADER_METHOD];\n const path = headers[HTTP2_HEADER_PATH];\n // ...\n stream.respond({\n [HTTP2_HEADER_STATUS]: 200,\n [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain'\n });\n stream.write('hello ');\n stream.end('world');\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'timeout'",
"type": "event",
"name": "timeout",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "The 'timeout'
event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2server.setTimeout()
.
If a 'request'
listener is registered or http2.createSecureServer()
\nis supplied a callback function, the 'checkContinue'
event is emitted each\ntime a request with an HTTP Expect: 100-continue
is received. If this event\nis not listened for, the server will automatically respond with a status\n100 Continue
as appropriate.
Handling this event involves calling response.writeContinue()
if the \nclient should continue to send the request body, or generating an appropriate \nHTTP response (e.g. 400 Bad Request) if the client should not continue to send \nthe request body.
Note that when this event is emitted and handled, the 'request'
event will\nnot be emitted.
Emitted each time there is a request. Note that there may be multiple requests\nper session. See the Compatibility API.
\n" }, { "textRaw": "Event: 'session'", "type": "event", "name": "session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "The 'session'
event is emitted when a new Http2Session
is created by the\nHttp2SecureServer
.
The 'sessionError'
event is emitted when an 'error'
event is emitted by\nan Http2Session
object associated with the Http2SecureServer
.
The 'stream'
event is emitted when a 'stream'
event has been emitted by\nan Http2Session
associated with the server.
const http2 = require('http2');\nconst {\n HTTP2_HEADER_METHOD,\n HTTP2_HEADER_PATH,\n HTTP2_HEADER_STATUS,\n HTTP2_HEADER_CONTENT_TYPE\n} = http2.constants;\n\nconst options = getOptionsSomehow();\n\nconst server = http2.createSecureServer(options);\nserver.on('stream', (stream, headers, flags) => {\n const method = headers[HTTP2_HEADER_METHOD];\n const path = headers[HTTP2_HEADER_PATH];\n // ...\n stream.respond({\n [HTTP2_HEADER_STATUS]: 200,\n [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain'\n });\n stream.write('hello ');\n stream.end('world');\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'timeout'",
"type": "event",
"name": "timeout",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "The 'timeout'
event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2secureServer.setTimeout()
.
The 'unknownProtocol'
event is emitted when a connecting client fails to\nnegotiate an allowed protocol (i.e. HTTP/2 or HTTP/1.1). The event handler\nreceives the socket for handling. If no listener is registered for this event,\nthe connection is terminated. See the Compatibility API.
Returns a net.Server
instance that creates and manages Http2Session
\ninstances.
Since there are no browsers known that support\nunencrypted HTTP/2, the use of\nhttp2.createSecureServer()
is necessary when communicating\nwith browser clients.
const http2 = require('http2');\n\n// Create an unencrypted HTTP/2 server.\n// Since there are no browsers known that support\n// unencrypted HTTP/2, the use of `http2.createSecureServer()`\n// is necessary when communicating with browser clients.\nconst server = http2.createServer();\n\nserver.on('stream', (stream, headers) => {\n stream.respond({\n 'content-type': 'text/html',\n ':status': 200\n });\n stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(80);\n
\n"
},
{
"textRaw": "http2.createSecureServer(options[, onRequestHandler])",
"type": "method",
"name": "createSecureServer",
"meta": {
"added": [
"v8.4.0"
],
"changes": [
{
"version": "v9.2.1",
"pr-url": "https://github.com/nodejs/node/pull/17105",
"description": "Added the `maxOutstandingPings` option with a default limit of 10."
},
{
"version": "v9.1.0",
"pr-url": "https://github.com/nodejs/node/pull/16676",
"description": "Added the `maxHeaderListPairs` option with a default limit of 128 header pairs."
}
]
},
"signatures": [
{
"return": {
"textRaw": "Returns {Http2SecureServer} ",
"name": "return",
"type": "Http2SecureServer"
},
"params": [
{
"textRaw": "`options` {Object} ",
"options": [
{
"textRaw": "`allowHTTP1` {boolean} Incoming client connections that do not support HTTP/2 will be downgraded to HTTP/1.x when set to `true`. **Default:** `false`. See the [`'unknownProtocol'`][] event. See [ALPN negotiation][]. ",
"name": "allowHTTP1",
"type": "boolean",
"desc": "Incoming client connections that do not support HTTP/2 will be downgraded to HTTP/1.x when set to `true`. **Default:** `false`. See the [`'unknownProtocol'`][] event. See [ALPN negotiation][]."
},
{
"textRaw": "`maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size for deflating header fields. **Default:** `4Kib` ",
"name": "maxDeflateDynamicTableSize",
"type": "number",
"desc": "Sets the maximum dynamic table size for deflating header fields. **Default:** `4Kib`"
},
{
"textRaw": "`maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. **Default:** `10`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged PING and SETTINGS frames are all counted towards the current limit. ",
"name": "maxSessionMemory",
"type": "number",
"desc": "Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. **Default:** `10`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged PING and SETTINGS frames are all counted towards the current limit."
},
{
"textRaw": "`maxHeaderListPairs` {number} Sets the maximum number of header entries. **Default:** `128`. The minimum value is `4`. ",
"name": "maxHeaderListPairs",
"type": "number",
"desc": "Sets the maximum number of header entries. **Default:** `128`. The minimum value is `4`."
},
{
"textRaw": "`maxOutstandingPings` {number} Sets the maximum number of outstanding, unacknowledged pings. The default is `10`. ",
"name": "maxOutstandingPings",
"type": "number",
"desc": "Sets the maximum number of outstanding, unacknowledged pings. The default is `10`."
},
{
"textRaw": "`maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed. ",
"name": "maxSendHeaderBlockLength",
"type": "number",
"desc": "Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed."
},
{
"textRaw": "`paddingStrategy` {number} Identifies the strategy used for determining the amount of padding to use for HEADERS and DATA frames. **Default:** `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of: ",
"options": [
{
"textRaw": "`http2.constants.PADDING_STRATEGY_NONE` - Specifies that no padding is to be applied. ",
"name": "http2.constants.PADDING_STRATEGY_NONE",
"desc": "Specifies that no padding is to be applied."
},
{
"textRaw": "`http2.constants.PADDING_STRATEGY_MAX` - Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied. ",
"name": "http2.constants.PADDING_STRATEGY_MAX",
"desc": "Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied."
},
{
"textRaw": "`http2.constants.PADDING_STRATEGY_CALLBACK` - Specifies that the user provided `options.selectPadding` callback is to be used to determine the amount of padding. ",
"name": "http2.constants.PADDING_STRATEGY_CALLBACK",
"desc": "Specifies that the user provided `options.selectPadding` callback is to be used to determine the amount of padding."
},
{
"textRaw": "`http2.constants.PADDING_STRATEGY_ALIGNED` - Will *attempt* to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will *not* necessarily be aligned at 8 bytes. ",
"name": "http2.constants.PADDING_STRATEGY_ALIGNED",
"desc": "Will *attempt* to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will *not* necessarily be aligned at 8 bytes."
}
],
"name": "paddingStrategy",
"type": "number",
"desc": "Identifies the strategy used for determining the amount of padding to use for HEADERS and DATA frames. **Default:** `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:"
},
{
"textRaw": "`peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent streams for the remote peer as if a SETTINGS frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. **Default:** `100` ",
"name": "peerMaxConcurrentStreams",
"type": "number",
"desc": "Sets the maximum number of concurrent streams for the remote peer as if a SETTINGS frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. **Default:** `100`"
},
{
"textRaw": "`selectPadding` {Function} When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using options.selectPadding][]. ",
"name": "selectPadding",
"type": "Function",
"desc": "When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using options.selectPadding][]."
},
{
"textRaw": "`settings` {HTTP/2 Settings Object} The initial settings to send to the remote peer upon connection. ",
"name": "settings",
"type": "HTTP/2 Settings Object",
"desc": "The initial settings to send to the remote peer upon connection."
},
{
"textRaw": "...: Any [`tls.createServer()`][] options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required. ",
"name": "...",
"desc": "Any [`tls.createServer()`][] options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required."
}
],
"name": "options",
"type": "Object"
},
{
"textRaw": "`onRequestHandler` {Function} See [Compatibility API][] ",
"name": "onRequestHandler",
"type": "Function",
"desc": "See [Compatibility API][]",
"optional": true
}
]
},
{
"params": [
{
"name": "options"
},
{
"name": "onRequestHandler",
"optional": true
}
]
}
],
"desc": "Returns a tls.Server
instance that creates and manages Http2Session
\ninstances.
const http2 = require('http2');\n\nconst options = {\n key: fs.readFileSync('server-key.pem'),\n cert: fs.readFileSync('server-cert.pem')\n};\n\n// Create a secure HTTP/2 server\nconst server = http2.createSecureServer(options);\n\nserver.on('stream', (stream, headers) => {\n stream.respond({\n 'content-type': 'text/html',\n ':status': 200\n });\n stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(80);\n
\n"
},
{
"textRaw": "http2.connect(authority[, options][, listener])",
"type": "method",
"name": "connect",
"meta": {
"added": [
"v8.4.0"
],
"changes": [
{
"version": "v9.2.1",
"pr-url": "https://github.com/nodejs/node/pull/17105",
"description": "Added the `maxOutstandingPings` option with a default limit of 10."
},
{
"version": "v9.1.0",
"pr-url": "https://github.com/nodejs/node/pull/16676",
"description": "Added the `maxHeaderListPairs` option with a default limit of 128 header pairs."
}
]
},
"signatures": [
{
"return": {
"textRaw": "Returns {ClientHttp2Session} ",
"name": "return",
"type": "ClientHttp2Session"
},
"params": [
{
"textRaw": "`authority` {string|URL} ",
"name": "authority",
"type": "string|URL"
},
{
"textRaw": "`options` {Object} ",
"options": [
{
"textRaw": "`maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size for deflating header fields. **Default:** `4Kib` ",
"name": "maxDeflateDynamicTableSize",
"type": "number",
"desc": "Sets the maximum dynamic table size for deflating header fields. **Default:** `4Kib`"
},
{
"textRaw": "`maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. **Default:** `10`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged PING and SETTINGS frames are all counted towards the current limit. ",
"name": "maxSessionMemory",
"type": "number",
"desc": "Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. **Default:** `10`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged PING and SETTINGS frames are all counted towards the current limit."
},
{
"textRaw": "`maxHeaderListPairs` {number} Sets the maximum number of header entries. **Default:** `128`. The minimum value is `1`. ",
"name": "maxHeaderListPairs",
"type": "number",
"desc": "Sets the maximum number of header entries. **Default:** `128`. The minimum value is `1`."
},
{
"textRaw": "`maxOutstandingPings` {number} Sets the maximum number of outstanding, unacknowledged pings. The default is `10`. ",
"name": "maxOutstandingPings",
"type": "number",
"desc": "Sets the maximum number of outstanding, unacknowledged pings. The default is `10`."
},
{
"textRaw": "`maxReservedRemoteStreams` {number} Sets the maximum number of reserved push streams the client will accept at any given time. Once the current number of currently reserved push streams exceeds reaches this limit, new push streams sent by the server will be automatically rejected. ",
"name": "maxReservedRemoteStreams",
"type": "number",
"desc": "Sets the maximum number of reserved push streams the client will accept at any given time. Once the current number of currently reserved push streams exceeds reaches this limit, new push streams sent by the server will be automatically rejected."
},
{
"textRaw": "`maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed. ",
"name": "maxSendHeaderBlockLength",
"type": "number",
"desc": "Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed."
},
{
"textRaw": "`paddingStrategy` {number} Identifies the strategy used for determining the amount of padding to use for HEADERS and DATA frames. **Default:** `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of: ",
"options": [
{
"textRaw": "`http2.constants.PADDING_STRATEGY_NONE` - Specifies that no padding is to be applied. ",
"name": "http2.constants.PADDING_STRATEGY_NONE",
"desc": "Specifies that no padding is to be applied."
},
{
"textRaw": "`http2.constants.PADDING_STRATEGY_MAX` - Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied. ",
"name": "http2.constants.PADDING_STRATEGY_MAX",
"desc": "Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied."
},
{
"textRaw": "`http2.constants.PADDING_STRATEGY_CALLBACK` - Specifies that the user provided `options.selectPadding` callback is to be used to determine the amount of padding. ",
"name": "http2.constants.PADDING_STRATEGY_CALLBACK",
"desc": "Specifies that the user provided `options.selectPadding` callback is to be used to determine the amount of padding."
},
{
"textRaw": "`http2.constants.PADDING_STRATEGY_ALIGNED` - Will *attempt* to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will *not* necessarily be aligned at 8 bytes. ",
"name": "http2.constants.PADDING_STRATEGY_ALIGNED",
"desc": "Will *attempt* to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will *not* necessarily be aligned at 8 bytes."
}
],
"name": "paddingStrategy",
"type": "number",
"desc": "Identifies the strategy used for determining the amount of padding to use for HEADERS and DATA frames. **Default:** `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:"
},
{
"textRaw": "`peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent streams for the remote peer as if a SETTINGS frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. **Default:** `100` ",
"name": "peerMaxConcurrentStreams",
"type": "number",
"desc": "Sets the maximum number of concurrent streams for the remote peer as if a SETTINGS frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. **Default:** `100`"
},
{
"textRaw": "`selectPadding` {Function} When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using options.selectPadding][]. ",
"name": "selectPadding",
"type": "Function",
"desc": "When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using options.selectPadding][]."
},
{
"textRaw": "`settings` {HTTP/2 Settings Object} The initial settings to send to the remote peer upon connection. ",
"name": "settings",
"type": "HTTP/2 Settings Object",
"desc": "The initial settings to send to the remote peer upon connection."
},
{
"textRaw": "`createConnection` {Function} An optional callback that receives the `URL` instance passed to `connect` and the `options` object, and returns any [`Duplex`][] stream that is to be used as the connection for this session. ",
"name": "createConnection",
"type": "Function",
"desc": "An optional callback that receives the `URL` instance passed to `connect` and the `options` object, and returns any [`Duplex`][] stream that is to be used as the connection for this session."
},
{
"textRaw": "...: Any [`net.connect()`][] or [`tls.connect()`][] options can be provided. ",
"name": "...",
"desc": "Any [`net.connect()`][] or [`tls.connect()`][] options can be provided."
}
],
"name": "options",
"type": "Object",
"optional": true
},
{
"textRaw": "`listener` {Function} ",
"name": "listener",
"type": "Function",
"optional": true
}
]
},
{
"params": [
{
"name": "authority"
},
{
"name": "options",
"optional": true
},
{
"name": "listener",
"optional": true
}
]
}
],
"desc": "Returns a ClientHttp2Session
instance.
const http2 = require('http2');\nconst client = http2.connect('https://localhost:1234');\n\n/** use the client **/\n\nclient.close();\n
\n"
},
{
"textRaw": "http2.getDefaultSettings()",
"type": "method",
"name": "getDefaultSettings",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {HTTP/2 Settings Object} ",
"name": "return",
"type": "HTTP/2 Settings Object"
},
"params": []
},
{
"params": []
}
],
"desc": "Returns an object containing the default settings for an Http2Session
\ninstance. This method returns a new object instance every time it is called\nso instances returned may be safely modified for use.
Returns a Buffer
instance containing serialized representation of the given\nHTTP/2 settings as specified in the HTTP/2 specification. This is intended\nfor use with the HTTP2-Settings
header field.
const http2 = require('http2');\n\nconst packed = http2.getPackedSettings({ enablePush: false });\n\nconsole.log(packed.toString('base64'));\n// Prints: AAIAAAAA\n
\n"
},
{
"textRaw": "http2.getUnpackedSettings(buf)",
"type": "method",
"name": "getUnpackedSettings",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {HTTP/2 Settings Object} ",
"name": "return",
"type": "HTTP/2 Settings Object"
},
"params": [
{
"textRaw": "`buf` {Buffer|Uint8Array} The packed settings. ",
"name": "buf",
"type": "Buffer|Uint8Array",
"desc": "The packed settings."
}
]
},
{
"params": [
{
"name": "buf"
}
]
}
],
"desc": "Returns a HTTP/2 Settings Object containing the deserialized settings from\nthe given Buffer
as generated by http2.getPackedSettings()
.
Value | \nName | \nConstant | \n
---|---|---|
0x00 | \nNo Error | \nhttp2.constants.NGHTTP2_NO_ERROR | \n
0x01 | \nProtocol Error | \nhttp2.constants.NGHTTP2_PROTOCOL_ERROR | \n
0x02 | \nInternal Error | \nhttp2.constants.NGHTTP2_INTERNAL_ERROR | \n
0x03 | \nFlow Control Error | \nhttp2.constants.NGHTTP2_FLOW_CONTROL_ERROR | \n
0x04 | \nSettings Timeout | \nhttp2.constants.NGHTTP2_SETTINGS_TIMEOUT | \n
0x05 | \nStream Closed | \nhttp2.constants.NGHTTP2_STREAM_CLOSED | \n
0x06 | \nFrame Size Error | \nhttp2.constants.NGHTTP2_FRAME_SIZE_ERROR | \n
0x07 | \nRefused Stream | \nhttp2.constants.NGHTTP2_REFUSED_STREAM | \n
0x08 | \nCancel | \nhttp2.constants.NGHTTP2_CANCEL | \n
0x09 | \nCompression Error | \nhttp2.constants.NGHTTP2_COMPRESSION_ERROR | \n
0x0a | \nConnect Error | \nhttp2.constants.NGHTTP2_CONNECT_ERROR | \n
0x0b | \nEnhance Your Calm | \nhttp2.constants.NGHTTP2_ENHANCE_YOUR_CALM | \n
0x0c | \nInadequate Security | \nhttp2.constants.NGHTTP2_INADEQUATE_SECURITY | \n
0x0d | \nHTTP/1.1 Required | \nhttp2.constants.NGHTTP2_HTTP_1_1_REQUIRED | \n
The 'timeout'
event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2server.setTimeout()
.
When options.paddingStrategy
is equal to\nhttp2.constants.PADDING_STRATEGY_CALLBACK
, the HTTP/2 implementation will\nconsult the options.selectPadding
callback function, if provided, to determine\nthe specific amount of padding to use per HEADERS and DATA frame.
The options.selectPadding
function receives two numeric arguments,\nframeLen
and maxFrameLen
and must return a number N
such that\nframeLen <= N <= maxFrameLen
.
const http2 = require('http2');\nconst server = http2.createServer({\n paddingStrategy: http2.constants.PADDING_STRATEGY_CALLBACK,\n selectPadding(frameLen, maxFrameLen) {\n return maxFrameLen;\n }\n});\n
\nThe options.selectPadding
function is invoked once for every HEADERS and\nDATA frame. This has a definite noticeable impact on performance.
The Compatibility API has the goal of providing a similar developer experience\nof HTTP/1 when using HTTP/2, making it possible to develop applications\nthat support both HTTP/1 and HTTP/2. This API targets only the\npublic API of the HTTP/1. However many modules use internal\nmethods or state, and those are not supported as it is a completely\ndifferent implementation.
\nThe following example creates an HTTP/2 server using the compatibility\nAPI:
\nconst http2 = require('http2');\nconst server = http2.createServer((req, res) => {\n res.setHeader('Content-Type', 'text/html');\n res.setHeader('X-Foo', 'bar');\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('ok');\n});\n
\nIn order to create a mixed HTTPS and HTTP/2 server, refer to the\nALPN negotiation section.\nUpgrading from non-tls HTTP/1 servers is not supported.
\nThe HTTP/2 compatibility API is composed of Http2ServerRequest
and\nHttp2ServerResponse
. They aim at API compatibility with HTTP/1, but\nthey do not hide the differences between the protocols. As an example,\nthe status message for HTTP codes is ignored.
ALPN negotiation allows supporting both HTTPS and HTTP/2 over\nthe same socket. The req
and res
objects can be either HTTP/1 or\nHTTP/2, and an application must restrict itself to the public API of\nHTTP/1, and detect if it is possible to use the more advanced\nfeatures of HTTP/2.
The following example creates a server that supports both protocols:
\nconst { createSecureServer } = require('http2');\nconst { readFileSync } = require('fs');\n\nconst cert = readFileSync('./cert.pem');\nconst key = readFileSync('./key.pem');\n\nconst server = createSecureServer(\n { cert, key, allowHTTP1: true },\n onRequest\n).listen(4443);\n\nfunction onRequest(req, res) {\n // detects if it is a HTTPS request or HTTP/2\n const { socket: { alpnProtocol } } = req.httpVersion === '2.0' ?\n req.stream.session : req;\n res.writeHead(200, { 'content-type': 'application/json' });\n res.end(JSON.stringify({\n alpnProtocol,\n httpVersion: req.httpVersion\n }));\n}\n
\nThe 'request'
event works identically on both HTTPS and\nHTTP/2.
A Http2ServerRequest
object is created by http2.Server
or\nhttp2.SecureServer
and passed as the first argument to the\n'request'
event. It may be used to access a request status, headers, and\ndata.
It implements the Readable Stream interface, as well as the\nfollowing additional events, methods, and properties.
\n", "events": [ { "textRaw": "Event: 'aborted'", "type": "event", "name": "aborted", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "The 'aborted'
event is emitted whenever a Http2ServerRequest
instance is\nabnormally aborted in mid-communication.
The 'aborted'
event will only be emitted if the Http2ServerRequest
writable\nside has not been ended.
Indicates that the underlying Http2Stream
was closed.\nJust like 'end'
, this event occurs only once per response.
Calls destroy()
on the Http2Stream
that received\nthe Http2ServerRequest
. If error
is provided, an 'error'
event\nis emitted and error
is passed as an argument to any listeners on the event.
It does nothing if the stream was already destroyed.
\n" }, { "textRaw": "request.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {number} ", "name": "msecs", "type": "number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "desc": "Sets the Http2Stream
's timeout value to msecs
. If a callback is\nprovided, then it is added as a listener on the 'timeout'
event on\nthe response object.
If no 'timeout'
listener is added to the request, the response, or\nthe server, then Http2Stream
s are destroyed when they time out. If a\nhandler is assigned to the request, the response, or the server's 'timeout'
\nevents, timed out sockets must be handled explicitly.
Returns request
.
The request/response headers object.
\nKey-value pairs of header names and values. Header names are lower-cased.\nExample:
\n// Prints something like:\n//\n// { 'user-agent': 'curl/7.22.0',\n// host: '127.0.0.1:8000',\n// accept: '*/*' }\nconsole.log(request.headers);\n
\n\nIn HTTP/2, the request path, hostname, protocol, and method are represented as\nspecial headers prefixed with the :
character (e.g. ':path'
). These special\nheaders will be included in the request.headers
object. Care must be taken not\nto inadvertently modify these special headers or errors may occur. For instance,\nremoving all headers from the request will cause errors to occur:
removeAllHeaders(request.headers);\nassert(request.url); // Fails because the :path header has been removed\n
\n"
},
{
"textRaw": "`httpVersion` {string} ",
"type": "string",
"name": "httpVersion",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "In case of server request, the HTTP version sent by the client. In the case of\nclient response, the HTTP version of the connected-to server. Returns\n'2.0'
.
Also message.httpVersionMajor
is the first integer and\nmessage.httpVersionMinor
is the second.
The request method as a string. Read-only. Example:\n'GET'
, 'DELETE'
.
The raw request/response headers list exactly as they were received.
\nNote that the keys and values are in the same list. It is not a\nlist of tuples. So, the even-numbered offsets are key values, and the\nodd-numbered offsets are the associated values.
\nHeader names are not lowercased, and duplicates are not merged.
\n// Prints something like:\n//\n// [ 'user-agent',\n// 'this is invalid because there can be only one',\n// 'User-Agent',\n// 'curl/7.22.0',\n// 'Host',\n// '127.0.0.1:8000',\n// 'ACCEPT',\n// '*/*' ]\nconsole.log(request.rawHeaders);\n
\n"
},
{
"textRaw": "`rawTrailers` {Array} ",
"type": "Array",
"name": "rawTrailers",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "The raw request/response trailer keys and values exactly as they were\nreceived. Only populated at the 'end'
event.
Returns a Proxy object that acts as a net.Socket
(or tls.TLSSocket
) but\napplies getters, setters, and methods based on HTTP/2 logic.
destroyed
, readable
, and writable
properties will be retrieved from and\nset on request.stream
.
destroy
, emit
, end
, on
and once
methods will be called on\nrequest.stream
.
setTimeout
method will be called on request.stream.session
.
pause
, read
, resume
, and write
will throw an error with code\nERR_HTTP2_NO_SOCKET_MANIPULATION
. See Http2Session and Sockets for\nmore information.
All other interactions will be routed directly to the socket. With TLS support,\nuse request.socket.getPeerCertificate()
to obtain the client's\nauthentication details.
The Http2Stream
object backing the request.
The request/response trailers object. Only populated at the 'end'
event.
Request URL string. This contains only the URL that is\npresent in the actual HTTP request. If the request is:
\nGET /status?name=ryan HTTP/1.1\\r\\n\nAccept: text/plain\\r\\n\n\\r\\n\n
\nThen request.url
will be:
'/status?name=ryan'\n
\nTo parse the url into its parts require('url').parse(request.url)
\ncan be used. Example:
$ node\n> require('url').parse('/status?name=ryan')\nUrl {\n protocol: null,\n slashes: null,\n auth: null,\n host: null,\n port: null,\n hostname: null,\n hash: null,\n search: '?name=ryan',\n query: 'name=ryan',\n pathname: '/status',\n path: '/status?name=ryan',\n href: '/status?name=ryan' }\n
\nTo extract the parameters from the query string, the\nrequire('querystring').parse
function can be used, or\ntrue
can be passed as the second argument to require('url').parse
.\nExample:
$ node\n> require('url').parse('/status?name=ryan', true)\nUrl {\n protocol: null,\n slashes: null,\n auth: null,\n host: null,\n port: null,\n hostname: null,\n hash: null,\n search: '?name=ryan',\n query: { name: 'ryan' },\n pathname: '/status',\n path: '/status?name=ryan',\n href: '/status?name=ryan' }\n
\n"
}
]
},
{
"textRaw": "Class: http2.Http2ServerResponse",
"type": "class",
"name": "http2.Http2ServerResponse",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "This object is created internally by an HTTP server--not by the user. It is\npassed as the second parameter to the 'request'
event.
The response implements, but does not inherit from, the Writable Stream\ninterface. This is an EventEmitter
with the following events:
Indicates that the underlying Http2Stream
was terminated before\nresponse.end()
was called or able to flush.
Emitted when the response has been sent. More specifically, this event is\nemitted when the last segment of the response headers and body have been\nhanded off to the HTTP/2 multiplexing for transmission over the network. It\ndoes not imply that the client has received anything yet.
\nAfter this event, no more events will be emitted on the response object.
\n", "params": [] } ], "methods": [ { "textRaw": "response.addTrailers(headers)", "type": "method", "name": "addTrailers", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {Object} ", "name": "headers", "type": "Object" } ] }, { "params": [ { "name": "headers" } ] } ], "desc": "This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.
\nAttempting to set a header field name or value that contains invalid characters\nwill result in a TypeError
being thrown.
This method signals to the server that all of the response headers and body\nhave been sent; that server should consider this message complete.\nThe method, response.end()
, MUST be called on each response.
If data
is specified, it is equivalent to calling\nresponse.write(data, encoding)
followed by response.end(callback)
.
If callback
is specified, it will be called when the response stream\nis finished.
Reads out a header that has already been queued but not sent to the client.\nNote that the name is case insensitive.
\nExample:
\nconst contentType = response.getHeader('content-type');\n
\n"
},
{
"textRaw": "response.getHeaderNames()",
"type": "method",
"name": "getHeaderNames",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Array} ",
"name": "return",
"type": "Array"
},
"params": []
},
{
"params": []
}
],
"desc": "Returns an array containing the unique names of the current outgoing headers.\nAll header names are lowercase.
\nExample:
\nresponse.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headerNames = response.getHeaderNames();\n// headerNames === ['foo', 'set-cookie']\n
\n"
},
{
"textRaw": "response.getHeaders()",
"type": "method",
"name": "getHeaders",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Object} ",
"name": "return",
"type": "Object"
},
"params": []
},
{
"params": []
}
],
"desc": "Returns a shallow copy of the current outgoing headers. Since a shallow copy\nis used, array values may be mutated without additional calls to various\nheader-related http module methods. The keys of the returned object are the\nheader names and the values are the respective header values. All header names\nare lowercase.
\nThe object returned by the response.getHeaders()
method does not\nprototypically inherit from the JavaScript Object
. This means that typical\nObject
methods such as obj.toString()
, obj.hasOwnProperty()
, and others\nare not defined and will not work.
Example:
\nresponse.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headers = response.getHeaders();\n// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }\n
\n"
},
{
"textRaw": "response.hasHeader(name)",
"type": "method",
"name": "hasHeader",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {boolean} ",
"name": "return",
"type": "boolean"
},
"params": [
{
"textRaw": "`name` {string} ",
"name": "name",
"type": "string"
}
]
},
{
"params": [
{
"name": "name"
}
]
}
],
"desc": "Returns true
if the header identified by name
is currently set in the\noutgoing headers. Note that the header name matching is case-insensitive.
Example:
\nconst hasContentType = response.hasHeader('content-type');\n
\n"
},
{
"textRaw": "response.removeHeader(name)",
"type": "method",
"name": "removeHeader",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string} ",
"name": "name",
"type": "string"
}
]
},
{
"params": [
{
"name": "name"
}
]
}
],
"desc": "Removes a header that has been queued for implicit sending.
\nExample:
\nresponse.removeHeader('Content-Encoding');\n
\n"
},
{
"textRaw": "response.setHeader(name, value)",
"type": "method",
"name": "setHeader",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string} ",
"name": "name",
"type": "string"
},
{
"textRaw": "`value` {string|string[]} ",
"name": "value",
"type": "string|string[]"
}
]
},
{
"params": [
{
"name": "name"
},
{
"name": "value"
}
]
}
],
"desc": "Sets a single header value for implicit headers. If this header already exists\nin the to-be-sent headers, its value will be replaced. Use an array of strings\nhere to send multiple headers with the same name.
\nExample:
\nresponse.setHeader('Content-Type', 'text/html');\n
\nor
\nresponse.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\n
\nAttempting to set a header field name or value that contains invalid characters\nwill result in a TypeError
being thrown.
When headers have been set with response.setHeader()
, they will be merged\nwith any headers passed to response.writeHead()
, with the headers passed\nto response.writeHead()
given precedence.
// returns content-type = text/plain\nconst server = http2.createServer((req, res) => {\n res.setHeader('Content-Type', 'text/html');\n res.setHeader('X-Foo', 'bar');\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('ok');\n});\n
\n"
},
{
"textRaw": "response.setTimeout(msecs[, callback])",
"type": "method",
"name": "setTimeout",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`msecs` {number} ",
"name": "msecs",
"type": "number"
},
{
"textRaw": "`callback` {Function} ",
"name": "callback",
"type": "Function",
"optional": true
}
]
},
{
"params": [
{
"name": "msecs"
},
{
"name": "callback",
"optional": true
}
]
}
],
"desc": "Sets the Http2Stream
's timeout value to msecs
. If a callback is\nprovided, then it is added as a listener on the 'timeout'
event on\nthe response object.
If no 'timeout'
listener is added to the request, the response, or\nthe server, then Http2Stream
s are destroyed when they time out. If a\nhandler is assigned to the request, the response, or the server's 'timeout'
\nevents, timed out sockets must be handled explicitly.
Returns response
.
If this method is called and response.writeHead()
has not been called,\nit will switch to implicit header mode and flush the implicit headers.
This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.
\nNote that in the http
module, the response body is omitted when the\nrequest is a HEAD request. Similarly, the 204
and 304
responses\nmust not include a message body.
chunk
can be a string or a buffer. If chunk
is a string,\nthe second parameter specifies how to encode it into a byte stream.\nBy default the encoding
is 'utf8'
. callback
will be called when this chunk\nof data is flushed.
This is the raw HTTP body and has nothing to do with higher-level multi-part\nbody encodings that may be used.
\nThe first time response.write()
is called, it will send the buffered\nheader information and the first chunk of the body to the client. The second\ntime response.write()
is called, Node.js assumes data will be streamed,\nand sends the new data separately. That is, the response is buffered up to the\nfirst chunk of the body.
Returns true
if the entire data was flushed successfully to the kernel\nbuffer. Returns false
if all or part of the data was queued in user memory.\n'drain'
will be emitted when the buffer is free again.
Sends a status 100 Continue
to the client, indicating that the request body\nshould be sent. See the 'checkContinue'
event on Http2Server
and\nHttp2SecureServer
.
Sends a response header to the request. The status code is a 3-digit HTTP\nstatus code, like 404
. The last argument, headers
, are the response headers.
For compatibility with HTTP/1, a human-readable statusMessage
may be\npassed as the second argument. However, because the statusMessage
has no\nmeaning within HTTP/2, the argument will have no effect and a process warning\nwill be emitted.
Example:
\nconst body = 'hello world';\nresponse.writeHead(200, {\n 'Content-Length': Buffer.byteLength(body),\n 'Content-Type': 'text/plain' });\n
\nNote that Content-Length is given in bytes not characters. The\nBuffer.byteLength()
API may be used to determine the number of bytes in a\ngiven encoding. On outbound messages, Node.js does not check if Content-Length\nand the length of the body being transmitted are equal or not. However, when\nreceiving messages, Node.js will automatically reject messages when the\nContent-Length does not match the actual payload size.
This method may be called at most one time on a message before\nresponse.end()
is called.
If response.write()
or response.end()
are called before calling\nthis, the implicit/mutable headers will be calculated and call this function.
When headers have been set with response.setHeader()
, they will be merged\nwith any headers passed to response.writeHead()
, with the headers passed\nto response.writeHead()
given precedence.
// returns content-type = text/plain\nconst server = http2.createServer((req, res) => {\n res.setHeader('Content-Type', 'text/html');\n res.setHeader('X-Foo', 'bar');\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('ok');\n});\n
\nAttempting to set a header field name or value that contains invalid characters\nwill result in a TypeError
being thrown.
Call http2stream.pushStream()
with the given headers, and wraps the\ngiven newly created Http2Stream
on Http2ServerRespose
.
The callback will be called with an error with code ERR_HTTP2_STREAM_CLOSED
\nif the stream is closed.
See response.socket
.
Boolean value that indicates whether the response has completed. Starts\nas false
. After response.end()
executes, the value will be true
.
Boolean (read-only). True if headers were sent, false otherwise.
\n" }, { "textRaw": "`sendDate` {boolean} ", "type": "boolean", "name": "sendDate", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "When true, the Date header will be automatically generated and sent in\nthe response if it is not already present in the headers. Defaults to true.
\nThis should only be disabled for testing; HTTP requires the Date header\nin responses.
\n" }, { "textRaw": "`socket` {net.Socket|tls.TLSSocket} ", "type": "net.Socket|tls.TLSSocket", "name": "socket", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "Returns a Proxy object that acts as a net.Socket
(or tls.TLSSocket
) but\napplies getters, setters, and methods based on HTTP/2 logic.
destroyed
, readable
, and writable
properties will be retrieved from and\nset on response.stream
.
destroy
, emit
, end
, on
and once
methods will be called on\nresponse.stream
.
setTimeout
method will be called on response.stream.session
.
pause
, read
, resume
, and write
will throw an error with code\nERR_HTTP2_NO_SOCKET_MANIPULATION
. See Http2Session and Sockets for\nmore information.
All other interactions will be routed directly to the socket.
\nExample:
\nconst http2 = require('http2');\nconst server = http2.createServer((req, res) => {\n const ip = req.socket.remoteAddress;\n const port = req.socket.remotePort;\n res.end(`Your IP address is ${ip} and your source port is ${port}.`);\n}).listen(3000);\n
\n"
},
{
"textRaw": "`statusCode` {number} ",
"type": "number",
"name": "statusCode",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "When using implicit headers (not calling response.writeHead()
explicitly),\nthis property controls the status code that will be sent to the client when\nthe headers get flushed.
Example:
\nresponse.statusCode = 404;\n
\nAfter response header was sent to the client, this property indicates the\nstatus code which was sent out.
\n" }, { "textRaw": "`statusMessage` {string} ", "type": "string", "name": "statusMessage", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "Status message is not supported by HTTP/2 (RFC7540 8.1.2.4). It returns\nan empty string.
\n" }, { "textRaw": "`stream` {http2.Http2Stream} ", "type": "http2.Http2Stream", "name": "stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "The Http2Stream
object backing the response.
The Performance Observer API can be used to collect basic performance\nmetrics for each Http2Session
and Http2Stream
instance.
const { PerformanceObserver } = require('perf_hooks');\n\nconst obs = new PerformanceObserver((items) => {\n const entry = items.getEntries()[0];\n console.log(entry.entryType); // prints 'http2'\n if (entry.name === 'Http2Session') {\n // entry contains statistics about the Http2Session\n } else if (entry.name === 'Http2Stream') {\n // entry contains statistics about the Http2Stream\n }\n});\nobs.observe({ entryTypes: ['http2'] });\n
\nThe entryType
property of the PerformanceEntry
will be equal to 'http2'
.
The name
property of the PerformanceEntry
will be equal to either\n'Http2Stream'
or 'Http2Session'
.
If name
is equal to Http2Stream
, the PerformanceEntry
will contain the\nfollowing additional properties:
bytesRead
{number} The number of DATA frame bytes received for this\nHttp2Stream
.bytesWritten
{number} The number of DATA frame bytes sent for this\nHttp2Stream
.id
{number} The identifier of the associated Http2Stream
timeToFirstByte
{number} The number of milliseconds elapsed between the\nPerformanceEntry
startTime
and the reception of the first DATA
frame.timeToFirstByteSent
{number} The number of milliseconds elapsed between\nthe PerformanceEntry
startTime
and sending of the first DATA
frame.timeToFirstHeader
{number} The number of milliseconds elapsed between the\nPerformanceEntry
startTime
and the reception of the first header.If name
is equal to Http2Session
, the PerformanceEntry
will contain the\nfollowing additional properties:
bytesRead
{number} The number of bytes received for this Http2Session
.bytesWritten
{number} The number of bytes sent for this Http2Session
.framesReceived
{number} The number of HTTP/2 frames received by the\nHttp2Session
.framesSent
{number} The number of HTTP/2 frames sent by the Http2Session
.maxConcurrentStreams
{number} The maximum number of streams concurrently\nopen during the lifetime of the Http2Session
.pingRTT
{number} The number of milliseconds elapsed since the transmission\nof a PING
frame and the reception of its acknowledgment. Only present if\na PING
frame has been sent on the Http2Session
.streamAverageDuration
{number} The average duration (in milliseconds) for\nall Http2Stream
instances.streamCount
{number} The number of Http2Stream
instances processed by\nthe Http2Session
.type
{string} Either 'server'
or 'client'
to identify the type of\nHttp2Session
.