{ "type": "module", "source": "doc/api/http2.md", "modules": [ { "textRaw": "HTTP/2", "name": "http/2", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/22466", "description": "HTTP/2 is now Stable. Previously, it had been Experimental." } ] }, "introduced_in": "v8.4.0", "stability": 2, "stabilityText": "Stable", "desc": "

The http2 module provides an implementation of the HTTP/2 protocol. It\ncan be accessed using:

\n
const http2 = require('http2');\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.

\n

The http2 Core API is much more symmetric between client and server than the\nhttp API. For instance, most events, like 'error', 'connect' and\n'stream', can be emitted either by client-side code or server-side code.

", "modules": [ { "textRaw": "Server-side example", "name": "server-side_example", "desc": "

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.

\n
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
\n

To generate the certificate and key for this example, run:

\n
openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \\\n  -keyout localhost-privkey.pem -out localhost-cert.pem\n
", "type": "module", "displayName": "Server-side example" }, { "textRaw": "Client-side example", "name": "client-side_example", "desc": "

The following illustrates an HTTP/2 client:

\n
const 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
", "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).

\n
const headers = {\n  ':status': '200',\n  'content-type': 'text-plain',\n  'ABC': ['has', 'more', 'than', 'one', 'value']\n};\n\nstream.respond(headers);\n
\n

Header 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.

\n

For incoming headers:

\n\n
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
", "type": "module", "displayName": "Headers Object" }, { "textRaw": "Settings Object", "name": "settings_object", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v8.9.3", "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.

\n\n

All additional properties on the settings object are ignored.

", "type": "module", "displayName": "Settings Object" }, { "textRaw": "Using `options.selectPadding()`", "name": "using_`options.selectpadding()`", "desc": "

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\ndetermine the specific amount of padding to use per HEADERS and DATA frame.

\n

The options.selectPadding() function receives two numeric arguments,\nframeLen and maxFrameLen and must return a number N such that\nframeLen <= N <= maxFrameLen.

\n
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
\n

The options.selectPadding() function is invoked once for every HEADERS and\nDATA frame. This has a definite noticeable impact on performance.

", "type": "module", "displayName": "Using `options.selectPadding()`" }, { "textRaw": "Error Handling", "name": "error_handling", "desc": "

There are several types of error conditions that may arise when using the\nhttp2 module:

\n

Validation errors occur when an incorrect argument, option, or setting value is\npassed in. These will always be reported by a synchronous throw.

\n

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.

\n

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.

\n

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.

", "type": "module", "displayName": "Error Handling" }, { "textRaw": "Invalid character handling in header names and values", "name": "invalid_character_handling_in_header_names_and_values", "desc": "

The HTTP/2 implementation applies stricter handling of invalid characters in\nHTTP header names and values than the HTTP/1 implementation.

\n

Header 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.

\n

Header field-names must only contain one or more of the following ASCII\ncharacters: a-z, A-Z, 0-9, !, #, $, %, &, ', *, +,\n-, ., ^, _, ` (backtick), |, and ~.

\n

Using invalid characters within an HTTP header field name will cause the\nstream to be closed with a protocol error being reported.

\n

Header 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.

", "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:

\n
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
", "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.

\n

A simple TCP Server:

\n
const 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
\n

An HTTP/2 CONNECT proxy:

\n
const http2 = require('http2');\nconst { NGHTTP2_REFUSED_STREAM } = http2.constants;\nconst net = require('net');\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
\n

An HTTP/2 CONNECT client:

\n
const 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
", "type": "module", "displayName": "Supporting the CONNECT method" }, { "textRaw": "The Extended CONNECT Protocol", "name": "the_extended_connect_protocol", "desc": "

RFC 8441 defines an \"Extended CONNECT Protocol\" extension to HTTP/2 that\nmay be used to bootstrap the use of an Http2Stream using the CONNECT\nmethod as a tunnel for other communication protocols (such as WebSockets).

\n

The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using\nthe enableConnectProtocol setting:

\n
const http2 = require('http2');\nconst settings = { enableConnectProtocol: true };\nconst server = http2.createServer({ settings });\n
\n

Once the client receives the SETTINGS frame from the server indicating that\nthe extended CONNECT may be used, it may send CONNECT requests that use the\n':protocol' HTTP/2 pseudo-header:

\n
const http2 = require('http2');\nconst client = http2.connect('http://localhost:8080');\nclient.on('remoteSettings', (settings) => {\n  if (settings.enableConnectProtocol) {\n    const req = client.request({ ':method': 'CONNECT', ':protocol': 'foo' });\n    // ...\n  }\n});\n
", "type": "module", "displayName": "The Extended CONNECT Protocol" } ], "classes": [ { "textRaw": "Class: Http2Session", "type": "class", "name": "Http2Session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

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.

\n

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.

\n

User code will not create Http2Session instances directly. Server-side\nHttp2Session instances are created by the Http2Server instance when a\nnew HTTP/2 connection is received. Client-side Http2Session instances are\ncreated using the http2.connect() method.

", "modules": [ { "textRaw": "Http2Session and Sockets", "name": "http2session_and_sockets", "desc": "

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.

\n

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.

\n

Once a Socket has been bound to an Http2Session, user code should rely\nsolely on the API of the Http2Session.

", "type": "module", "displayName": "Http2Session and Sockets" } ], "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'close' event is emitted once the Http2Session has been destroyed. Its\nlistener does not expect any arguments.

" }, { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`session` {Http2Session}", "name": "session", "type": "Http2Session" }, { "textRaw": "`socket` {net.Socket}", "name": "socket", "type": "net.Socket" } ], "desc": "

The 'connect' event is emitted once the Http2Session has been successfully\nconnected to the remote peer and communication may begin.

\n

User code will typically not listen for this event directly.

" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`error` {Error}", "name": "error", "type": "Error" } ], "desc": "

The 'error' event is emitted when an error occurs during the processing of\nan Http2Session.

" }, { "textRaw": "Event: 'frameError'", "type": "event", "name": "frameError", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`type` {integer} The frame type.", "name": "type", "type": "integer", "desc": "The frame type." }, { "textRaw": "`code` {integer} The error code.", "name": "code", "type": "integer", "desc": "The error code." }, { "textRaw": "`id` {integer} The stream id (or `0` if the frame isn't associated with a stream).", "name": "id", "type": "integer", "desc": "The stream id (or `0` if the frame isn't associated with a stream)." } ], "desc": "

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.

\n

If 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.

" }, { "textRaw": "Event: 'goaway'", "type": "event", "name": "goaway", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`errorCode` {number} The HTTP/2 error code specified in the `GOAWAY` frame.", "name": "errorCode", "type": "number", "desc": "The HTTP/2 error code specified in the `GOAWAY` frame." }, { "textRaw": "`lastStreamID` {number} The ID of the last stream the remote peer successfully processed (or `0` if no ID is specified).", "name": "lastStreamID", "type": "number", "desc": "The ID of the last stream the remote peer successfully processed (or `0` if no ID is specified)." }, { "textRaw": "`opaqueData` {Buffer} If additional opaque data was included in the `GOAWAY` frame, a `Buffer` instance will be passed containing that data.", "name": "opaqueData", "type": "Buffer", "desc": "If additional opaque data was included in the `GOAWAY` frame, a `Buffer` instance will be passed containing that data." } ], "desc": "

The 'goaway' event is emitted when a GOAWAY frame is received.

\n

The Http2Session instance will be shut down automatically when the 'goaway'\nevent is emitted.

" }, { "textRaw": "Event: 'localSettings'", "type": "event", "name": "localSettings", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received.", "name": "settings", "type": "HTTP/2 Settings Object", "desc": "A copy of the `SETTINGS` frame received." } ], "desc": "

The 'localSettings' event is emitted when an acknowledgment SETTINGS frame\nhas been received.

\n

When using http2session.settings() to submit new settings, the modified\nsettings do not take effect until the 'localSettings' event is emitted.

\n
session.settings({ enablePush: false });\n\nsession.on('localSettings', (settings) => {\n  /* Use the new settings */\n});\n
" }, { "textRaw": "Event: 'ping'", "type": "event", "name": "ping", "meta": { "added": [ "v10.12.0" ], "changes": [] }, "params": [ { "textRaw": "`payload` {Buffer} The `PING` frame 8-byte payload", "name": "payload", "type": "Buffer", "desc": "The `PING` frame 8-byte payload" } ], "desc": "

The 'ping' event is emitted whenever a PING frame is received from the\nconnected peer.

" }, { "textRaw": "Event: 'remoteSettings'", "type": "event", "name": "remoteSettings", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received.", "name": "settings", "type": "HTTP/2 Settings Object", "desc": "A copy of the `SETTINGS` frame received." } ], "desc": "

The 'remoteSettings' event is emitted when a new SETTINGS frame is received\nfrom the connected peer.

\n
session.on('remoteSettings', (settings) => {\n  /* Use the new settings */\n});\n
" }, { "textRaw": "Event: 'stream'", "type": "event", "name": "stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`stream` {Http2Stream} A reference to the stream", "name": "stream", "type": "Http2Stream", "desc": "A reference to the stream" }, { "textRaw": "`headers` {HTTP/2 Headers Object} An object describing the headers", "name": "headers", "type": "HTTP/2 Headers Object", "desc": "An object describing the headers" }, { "textRaw": "`flags` {number} The associated numeric flags", "name": "flags", "type": "number", "desc": "The associated numeric flags" }, { "textRaw": "`rawHeaders` {Array} An array containing the raw header names followed by their respective values.", "name": "rawHeaders", "type": "Array", "desc": "An array containing the raw header names followed by their respective values." } ], "desc": "

The 'stream' event is emitted when a new Http2Stream is created.

\n
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
\n

On 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:

\n
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.on('error', (error) => console.error(error));\n  stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(80);\n
\n

Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence,\na network error will destroy each individual stream and must be handled on the\nstream level, as shown above.

" }, { "textRaw": "Event: 'timeout'", "type": "event", "name": "timeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "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.

\n
session.setTimeout(2000);\nsession.on('timeout', () => { /* .. */ });\n
" } ], "properties": [ { "textRaw": "`alpnProtocol` {string|undefined}", "type": "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.

" }, { "textRaw": "`closed` {boolean}", "type": "boolean", "name": "closed", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

Will be true if this Http2Session instance has been closed, otherwise\nfalse.

" }, { "textRaw": "`connecting` {boolean}", "type": "boolean", "name": "connecting", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "desc": "

Will be true if this Http2Session instance is still connecting, will be set\nto false before emitting connect event and/or calling the http2.connect\ncallback.

" }, { "textRaw": "`destroyed` {boolean}", "type": "boolean", "name": "destroyed", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Will be true if this Http2Session instance has been destroyed and must no\nlonger be used, otherwise false.

" }, { "textRaw": "`encrypted` {boolean|undefined}", "type": "boolean|undefined", "name": "encrypted", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "`localSettings` {HTTP/2 Settings Object}", "type": "HTTP/2 Settings Object", "name": "localSettings", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

A prototype-less object describing the current local settings of this\nHttp2Session. The local settings are local to this Http2Session instance.

" }, { "textRaw": "`originSet` {string[]|undefined}", "type": "string[]|undefined", "name": "originSet", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

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.

\n

The originSet property is only available when using a secure TLS connection.

" }, { "textRaw": "`pendingSettingsAck` {boolean}", "type": "boolean", "name": "pendingSettingsAck", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "`remoteSettings` {HTTP/2 Settings Object}", "type": "HTTP/2 Settings Object", "name": "remoteSettings", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

A prototype-less object describing the current remote settings of this\nHttp2Session. The remote settings are set by the connected HTTP/2 peer.

" }, { "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\nlimits available methods to ones safe to use with HTTP/2.

\n

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.

\n

setTimeout method will be called on this Http2Session.

\n

All other interactions will be routed directly to the socket.

" }, { "textRaw": "http2session.state", "name": "state", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Provides miscellaneous information about the current state of the\nHttp2Session.

\n\n

An object describing the current status of this Http2Session.

" }, { "textRaw": "`type` {number}", "type": "number", "name": "type", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

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.

" } ], "methods": [ { "textRaw": "http2session.close([callback])", "type": "method", "name": "close", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ] } ], "desc": "

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.

\n

If specified, the callback function is registered as a handler for the\n'close' event.

" }, { "textRaw": "http2session.destroy([error][, code])", "type": "method", "name": "destroy", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`error` {Error} An `Error` object if the `Http2Session` is being destroyed due to an error.", "name": "error", "type": "Error", "desc": "An `Error` object if the `Http2Session` is being destroyed due to an error.", "optional": true }, { "textRaw": "`code` {number} The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`.", "name": "code", "type": "number", "desc": "The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`.", "optional": true } ] } ], "desc": "

Immediately terminates the Http2Session and the associated net.Socket or\ntls.TLSSocket.

\n

Once destroyed, the Http2Session will emit the 'close' event. If error\nis not undefined, an 'error' event will be emitted immediately before the\n'close' event.

\n

If there are any remaining open Http2Streams associated with the\nHttp2Session, those will also be destroyed.

" }, { "textRaw": "http2session.goaway([code[, lastStreamID[, opaqueData]]])", "type": "method", "name": "goaway", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`code` {number} An HTTP/2 error code", "name": "code", "type": "number", "desc": "An HTTP/2 error code", "optional": true }, { "textRaw": "`lastStreamID` {number} The numeric ID of the last processed `Http2Stream`", "name": "lastStreamID", "type": "number", "desc": "The numeric ID of the last processed `Http2Stream`", "optional": true }, { "textRaw": "`opaqueData` {Buffer|TypedArray|DataView} A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame.", "name": "opaqueData", "type": "Buffer|TypedArray|DataView", "desc": "A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame.", "optional": true } ] } ], "desc": "

Transmits a GOAWAY frame to the connected peer without shutting down the\nHttp2Session.

" }, { "textRaw": "http2session.ping([payload, ]callback)", "type": "method", "name": "ping", "meta": { "added": [ "v8.9.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`payload` {Buffer|TypedArray|DataView} Optional ping payload.", "name": "payload", "type": "Buffer|TypedArray|DataView", "desc": "Optional ping payload.", "optional": true }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

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.

\n

The maximum number of outstanding (unacknowledged) pings is determined by the\nmaxOutstandingPings configuration option. The default maximum is 10.

\n

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.

\n

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.

\n
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
\n

If the payload argument is not specified, the default payload will be the\n64-bit timestamp (little endian) marking the start of the PING duration.

" }, { "textRaw": "http2session.ref()", "type": "method", "name": "ref", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Calls ref() on this Http2Session\ninstance's underlying net.Socket.

" }, { "textRaw": "http2session.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" } ] } ], "desc": "

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.

" }, { "textRaw": "http2session.settings(settings)", "type": "method", "name": "settings", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`settings` {HTTP/2 Settings Object}", "name": "settings", "type": "HTTP/2 Settings Object" } ] } ], "desc": "

Updates the current local settings for this Http2Session and sends a new\nSETTINGS frame to the connected HTTP/2 peer.

\n

Once called, the http2session.pendingSettingsAck property will be true\nwhile the session is waiting for the remote peer to acknowledge the new\nsettings.

\n

The new settings will not become effective until the SETTINGS acknowledgment\nis received and the 'localSettings' event is emitted. It is possible to send\nmultiple SETTINGS frames while acknowledgment is still pending.

" }, { "textRaw": "http2session.unref()", "type": "method", "name": "unref", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Calls unref() on this Http2Session\ninstance's underlying net.Socket.

" } ] }, { "textRaw": "Class: ServerHttp2Session", "type": "class", "name": "ServerHttp2Session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "methods": [ { "textRaw": "serverhttp2session.altsvc(alt, originOrStream)", "type": "method", "name": "altsvc", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`alt` {string} A description of the alternative service configuration as defined by [RFC 7838][].", "name": "alt", "type": "string", "desc": "A description of the alternative service configuration as defined by [RFC 7838][]." }, { "textRaw": "`originOrStream` {number|string|URL|Object} Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the `http2stream.id` property.", "name": "originOrStream", "type": "number|string|URL|Object", "desc": "Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the `http2stream.id` property." } ] } ], "desc": "

Submits an ALTSVC frame (as defined by RFC 7838) to the connected client.

\n
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
\n

Sending an ALTSVC frame with a specific stream ID indicates that the alternate\nservice is associated with the origin of the given Http2Stream.

\n

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.

\n

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.

\n

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.

" }, { "textRaw": "serverhttp2session.origin(...origins)", "type": "method", "name": "origin", "meta": { "added": [ "v10.12.0" ], "changes": [] }, "signatures": [ { "params": [ { "name": "...origins" } ] } ], "desc": "

Submits an ORIGIN frame (as defined by RFC 8336) to the connected client\nto advertise the set of origins for which the server is capable of providing\nauthoritative responses.

\n
const http2 = require('http2');\nconst options = getSecureOptionsSomehow();\nconst server = http2.createSecureServer(options);\nserver.on('stream', (stream) => {\n  stream.respond();\n  stream.end('ok');\n});\nserver.on('session', (session) => {\n  session.origin('https://example.com', 'https://example.org');\n});\n
\n

When a string is passed as an origin, it will be parsed as a URL and the\norigin will be derived. For instance, the origin for the HTTP URL\n'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.

\n

A URL object, or any object with an origin property, may be passed as\nan origin, 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.

\n

Alternatively, the origins option may be used when creating a new HTTP/2\nserver using the http2.createSecureServer() method:

\n
const http2 = require('http2');\nconst options = getSecureOptionsSomehow();\noptions.origins = ['https://example.com', 'https://example.org'];\nconst server = http2.createSecureServer(options);\nserver.on('stream', (stream) => {\n  stream.respond();\n  stream.end('ok');\n});\n
" } ], "modules": [ { "textRaw": "Specifying alternative services", "name": "specifying_alternative_services", "desc": "

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.

\n

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.

\n

Multiple alternatives may be specified, for instance: 'h2=\"example.org:81\", h2=\":82\"'.

\n

The protocol identifier ('h2' in the examples) may be any valid\nALPN Protocol ID.

\n

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.

", "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": [ { "textRaw": "`alt` {string}", "name": "alt", "type": "string" }, { "textRaw": "`origin` {string}", "name": "origin", "type": "string" }, { "textRaw": "`streamId` {number}", "name": "streamId", "type": "number" } ], "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.

\n
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
" }, { "textRaw": "Event: 'origin'", "type": "event", "name": "origin", "meta": { "added": [ "v10.12.0" ], "changes": [] }, "params": [ { "textRaw": "`origins` {string[]}", "name": "origins", "type": "string[]" } ], "desc": "

The 'origin' event is emitted whenever an ORIGIN frame is received by\nthe client. The event is emitted with an array of origin strings. The\nhttp2session.originSet will be updated to include the received\norigins.

\n
const http2 = require('http2');\nconst client = http2.connect('https://example.org');\n\nclient.on('origin', (origins) => {\n  for (let n = 0; n < origins.length; n++)\n    console.log(origins[n]);\n});\n
\n

The 'origin' event is only emitted when using a secure TLS connection.

" } ], "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}", "name": "options", "type": "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", "default": "`false`", "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." }, { "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": "`waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent.", "name": "waitForTrailers", "type": "boolean", "desc": "When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent." } ], "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.

\n

This method is only available if http2session.type is equal to\nhttp2.constants.NGHTTP2_SESSION_CLIENT.

\n
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
\n

When the options.waitForTrailers option is set, the 'wantTrailers' event\nis emitted immediately after queuing the last chunk of payload data to be sent.\nThe http2stream.sendTrailers() method can then be called to send trailing\nheaders to the peer.

\n

When options.waitForTrailers is set, the Http2Stream will not automatically\nclose when the final DATA frame is transmitted. User code must call either\nhttp2stream.sendTrailers() or http2stream.close() to close the\nHttp2Stream.

\n

The :method and :path pseudo-headers are not specified within headers,\nthey respectively default to:

\n" } ] }, { "textRaw": "Class: Http2Stream", "type": "class", "name": "Http2Stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

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.

\n

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.

\n

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.

\n

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.

", "modules": [ { "textRaw": "Http2Stream Lifecycle", "name": "http2stream_lifecycle", "modules": [ { "textRaw": "Creation", "name": "creation", "desc": "

On the server side, instances of ServerHttp2Stream are created either\nwhen:

\n\n

On the client side, instances of ClientHttp2Stream are created when the\nhttp2session.request() method is called.

\n

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.

", "type": "module", "displayName": "Creation" }, { "textRaw": "Destruction", "name": "destruction", "desc": "

All Http2Stream instances are destroyed either when:

\n\n

When an Http2Stream instance is destroyed, an attempt will be made to send an\nRST_STREAM frame will be sent to the connected peer.

\n

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.

\n

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.

", "type": "module", "displayName": "Destruction" } ], "type": "module", "displayName": "Http2Stream Lifecycle" } ], "events": [ { "textRaw": "Event: 'aborted'", "type": "event", "name": "aborted", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'aborted' event is emitted whenever a Http2Stream instance is\nabnormally aborted in mid-communication.

\n

The 'aborted' event will only be emitted if the Http2Stream writable side\nhas not been ended.

" }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'close' event is emitted when the Http2Stream is destroyed. Once\nthis event is emitted, the Http2Stream instance is no longer usable.

\n

The HTTP/2 error code used when closing the stream can be retrieved using\nthe http2stream.rstCode property. If the code is any value other than\nNGHTTP2_NO_ERROR (0), an 'error' event will have also been emitted.

" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`error` {Error}", "name": "error", "type": "Error" } ], "desc": "

The 'error' event is emitted when an error occurs during the processing of\nan Http2Stream.

" }, { "textRaw": "Event: 'frameError'", "type": "event", "name": "frameError", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

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.

" }, { "textRaw": "Event: 'timeout'", "type": "event", "name": "timeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'timeout' event is emitted after no activity is received for this\nHttp2Stream within the number of milliseconds set using\nhttp2stream.setTimeout().

" }, { "textRaw": "Event: 'trailers'", "type": "event", "name": "trailers", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

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.

\n

Note that this event might not be emitted if http2stream.end() is called\nbefore trailers are received and the incoming data is not being read or\nlistened for.

\n
stream.on('trailers', (headers, flags) => {\n  console.log(headers);\n});\n
" }, { "textRaw": "Event: 'wantTrailers'", "type": "event", "name": "wantTrailers", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "params": [], "desc": "

The 'wantTrailers' event is emitted when the Http2Stream has queued the\nfinal DATA frame to be sent on a frame and the Http2Stream is ready to send\ntrailing headers. When initiating a request or response, the waitForTrailers\noption must be set for this event to be emitted.

" } ], "properties": [ { "textRaw": "`aborted` {boolean}", "type": "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.

" }, { "textRaw": "`closed` {boolean}", "type": "boolean", "name": "closed", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

Set to true if the Http2Stream instance has been closed.

" }, { "textRaw": "`destroyed` {boolean}", "type": "boolean", "name": "destroyed", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Set to true if the Http2Stream instance has been destroyed and is no longer\nusable.

" }, { "textRaw": "`endAfterHeaders` {boolean}", "type": "boolean", "name": "endAfterHeaders", "meta": { "added": [ "v10.11.0" ], "changes": [] }, "desc": "

Set the true if the END_STREAM flag was set in the request or response\nHEADERS frame received, indicating that no additional data should be received\nand the readable side of the Http2Stream will be closed.

" }, { "textRaw": "`pending` {boolean}", "type": "boolean", "name": "pending", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

Set to true if the Http2Stream instance has not yet been assigned a\nnumeric stream identifier.

" }, { "textRaw": "`rstCode` {number}", "type": "number", "name": "rstCode", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "`sentHeaders` {HTTP/2 Headers Object}", "type": "HTTP/2 Headers Object", "name": "sentHeaders", "meta": { "added": [ "v9.5.0" ], "changes": [] }, "desc": "

An object containing the outbound headers sent for this Http2Stream.

" }, { "textRaw": "`sentInfoHeaders` {HTTP/2 Headers Object[]}", "type": "HTTP/2 Headers Object[]", "name": "sentInfoHeaders", "meta": { "added": [ "v9.5.0" ], "changes": [] }, "desc": "

An array of objects containing the outbound informational (additional) headers\nsent for this Http2Stream.

" }, { "textRaw": "`sentTrailers` {HTTP/2 Headers Object}", "type": "HTTP/2 Headers Object", "name": "sentTrailers", "meta": { "added": [ "v9.5.0" ], "changes": [] }, "desc": "

An object containing the outbound trailers sent for this this HttpStream.

" }, { "textRaw": "`session` {Http2Session}", "type": "Http2Session", "name": "session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

A reference to the Http2Session instance that owns this Http2Stream. The\nvalue will be undefined after the Http2Stream instance is destroyed.

" }, { "textRaw": "http2stream.state", "name": "state", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Provides miscellaneous information about the current state of the\nHttp2Stream.

\n\n

A current state of this Http2Stream.

" } ], "methods": [ { "textRaw": "http2stream.close(code[, callback])", "type": "method", "name": "close", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`code` {number} Unsigned 32-bit integer identifying the error code. **Default:** `http2.constants.NGHTTP2_NO_ERROR` (`0x00`).", "name": "code", "type": "number", "default": "`http2.constants.NGHTTP2_NO_ERROR` (`0x00`)", "desc": "Unsigned 32-bit integer identifying the error code." }, { "textRaw": "`callback` {Function} An optional function registered to listen for the `'close'` event.", "name": "callback", "type": "Function", "desc": "An optional function registered to listen for the `'close'` event.", "optional": true } ] } ], "desc": "

Closes the Http2Stream instance by sending an RST_STREAM frame to the\nconnected HTTP/2 peer.

" }, { "textRaw": "http2stream.priority(options)", "type": "method", "name": "priority", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`exclusive` {boolean} When `true` and `parent` identifies a parent Stream, this stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of this stream. **Default:** `false`.", "name": "exclusive", "type": "boolean", "default": "`false`", "desc": "When `true` and `parent` identifies a parent Stream, this stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of this stream." }, { "textRaw": "`parent` {number} Specifies the numeric identifier of a stream this stream is dependent on.", "name": "parent", "type": "number", "desc": "Specifies the numeric identifier of a stream this 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": "`silent` {boolean} When `true`, changes the priority locally without sending a `PRIORITY` frame to the connected peer.", "name": "silent", "type": "boolean", "desc": "When `true`, changes the priority locally without sending a `PRIORITY` frame to the connected peer." } ] } ] } ], "desc": "

Updates the priority for this Http2Stream instance.

" }, { "textRaw": "http2stream.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" } ] } ], "desc": "
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
" }, { "textRaw": "http2stream.sendTrailers(headers)", "type": "method", "name": "sendTrailers", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object" } ] } ], "desc": "

Sends a trailing HEADERS frame to the connected HTTP/2 peer. This method\nwill cause the Http2Stream to be immediately closed and must only be\ncalled after the 'wantTrailers' event has been emitted. When sending a\nrequest or sending a response, the options.waitForTrailers option must be set\nin order to keep the Http2Stream open after the final DATA frame so that\ntrailers can be sent.

\n
const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  stream.respond(undefined, { waitForTrailers: true });\n  stream.on('wantTrailers', () => {\n    stream.sendTrailers({ xyz: 'abc' });\n  });\n  stream.end('Hello World');\n});\n
\n

The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header\nfields (e.g. ':method', ':path', etc).

" } ] }, { "textRaw": "Class: ClientHttp2Stream", "type": "class", "name": "ClientHttp2Stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

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.

", "events": [ { "textRaw": "Event: 'continue'", "type": "event", "name": "continue", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "params": [], "desc": "

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.

" }, { "textRaw": "Event: 'headers'", "type": "event", "name": "headers", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

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.

\n
stream.on('headers', (headers, flags) => {\n  console.log(headers);\n});\n
" }, { "textRaw": "Event: 'push'", "type": "event", "name": "push", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "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.

\n
stream.on('push', (headers, flags) => {\n  console.log(headers);\n});\n
" }, { "textRaw": "Event: 'response'", "type": "event", "name": "response", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "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.

\n
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
" } ] }, { "textRaw": "Class: ServerHttp2Stream", "type": "class", "name": "ServerHttp2Stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

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.

", "methods": [ { "textRaw": "http2stream.additionalHeaders(headers)", "type": "method", "name": "additionalHeaders", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object" } ] } ], "desc": "

Sends an additional informational HEADERS frame to the connected HTTP/2 peer.

" }, { "textRaw": "http2stream.pushStream(headers[, options], callback)", "type": "method", "name": "pushStream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "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", "default": "`false`", "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." }, { "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." } ], "optional": true }, { "textRaw": "`callback` {Function} Callback that is called once the push stream has been initiated.", "name": "callback", "type": "Function", "desc": "Callback that is called once the push stream has been initiated.", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`pushStream` {ServerHttp2Stream} The returned `pushStream` object.", "name": "pushStream", "type": "ServerHttp2Stream", "desc": "The returned `pushStream` object." }, { "textRaw": "`headers` {HTTP/2 Headers Object} Headers object the `pushStream` was initiated with.", "name": "headers", "type": "HTTP/2 Headers Object", "desc": "Headers object the `pushStream` was initiated with." } ] } ] } ], "desc": "

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.

\n
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
\n

Setting 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.

\n

Calling http2stream.pushStream() from within a pushed stream is not permitted\nand will throw an error.

" }, { "textRaw": "http2stream.respond([headers[, options]])", "type": "method", "name": "respond", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object", "optional": true }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`endStream` {boolean} Set to `true` to indicate that the response will not include payload data.", "name": "endStream", "type": "boolean", "desc": "Set to `true` to indicate that the response will not include payload data." }, { "textRaw": "`waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent.", "name": "waitForTrailers", "type": "boolean", "desc": "When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent." } ], "optional": true } ] } ], "desc": "
const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  stream.respond({ ':status': 200 });\n  stream.end('some data');\n});\n
\n

When the options.waitForTrailers option is set, the 'wantTrailers' event\nwill be emitted immediately after queuing the last chunk of payload data to be\nsent. The http2stream.sendTrailers() method can then be used to sent trailing\nheader fields to the peer.

\n

When options.waitForTrailers is set, the Http2Stream will not automatically\nclose when the final DATA frame is transmitted. User code must call either\nhttp2stream.sendTrailers() or http2stream.close() to close the\nHttp2Stream.

\n
const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  stream.respond({ ':status': 200 }, { waitForTrailers: true });\n  stream.on('wantTrailers', () => {\n    stream.sendTrailers({ ABC: 'some value to send' });\n  });\n  stream.end('some data');\n});\n
" }, { "textRaw": "http2stream.respondWithFD(fd[, headers[, options]])", "type": "method", "name": "respondWithFD", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18936", "description": "Any readable file descriptor, not necessarily for a regular file, is supported now." } ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {number} A readable file descriptor.", "name": "fd", "type": "number", "desc": "A readable file descriptor." }, { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object", "optional": true }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`statCheck` {Function}", "name": "statCheck", "type": "Function" }, { "textRaw": "`waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent.", "name": "waitForTrailers", "type": "boolean", "desc": "When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent." }, { "textRaw": "`offset` {number} The offset position at which to begin reading.", "name": "offset", "type": "number", "desc": "The offset position at which to begin reading." }, { "textRaw": "`length` {number} The amount of data from the fd to send.", "name": "length", "type": "number", "desc": "The amount of data from the fd to send." } ], "optional": true } ] } ], "desc": "

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.

\n

When used, the Http2Stream object's Duplex interface will be closed\nautomatically.

\n
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
\n

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 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.

\n

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.

\n

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.

\n

When the options.waitForTrailers option is set, the 'wantTrailers' event\nwill be emitted immediately after queuing the last chunk of payload data to be\nsent. The http2stream.sendTrailers() method can then be used to sent trailing\nheader fields to the peer.

\n

When options.waitForTrailers is set, the Http2Stream will not automatically\nclose when the final DATA frame is transmitted. User code must call either\nhttp2stream.sendTrailers() or http2stream.close() to close the\nHttp2Stream.

\n
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, { waitForTrailers: true });\n  stream.on('wantTrailers', () => {\n    stream.sendTrailers({ ABC: 'some value to send' });\n  });\n\n  stream.on('close', () => fs.closeSync(fd));\n});\n
" }, { "textRaw": "http2stream.respondWithFile(path[, headers[, options]])", "type": "method", "name": "respondWithFile", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18936", "description": "Any readable file, not necessarily a regular file, is supported now." } ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object", "optional": true }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`statCheck` {Function}", "name": "statCheck", "type": "Function" }, { "textRaw": "`onError` {Function} Callback function invoked in the case of an error before send.", "name": "onError", "type": "Function", "desc": "Callback function invoked in the case of an error before send." }, { "textRaw": "`waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent.", "name": "waitForTrailers", "type": "boolean", "desc": "When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent." }, { "textRaw": "`offset` {number} The offset position at which to begin reading.", "name": "offset", "type": "number", "desc": "The offset position at which to begin reading." }, { "textRaw": "`length` {number} The amount of data from the fd to send.", "name": "length", "type": "number", "desc": "The amount of data from the fd to send." } ], "optional": true } ] } ], "desc": "

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.

\n

When used, the Http2Stream object's Duplex interface will be closed\nautomatically.

\n

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:

\n

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.

\n

Example using a file path:

\n
const 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
\n

The 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:

\n
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
\n

The content-length header field will be automatically set.

\n

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.

\n

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.

\n

When the options.waitForTrailers option is set, the 'wantTrailers' event\nwill be emitted immediately after queuing the last chunk of payload data to be\nsent. The http2stream.sendTrilers() method can then be used to sent trailing\nheader fields to the peer.

\n

When options.waitForTrailers is set, the Http2Stream will not automatically\nclose when the final DATA frame is transmitted. User code must call either\nhttp2stream.sendTrailers() or http2stream.close() to close the\nHttp2Stream.

\n
const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  stream.respondWithFile('/some/file',\n                         { 'content-type': 'text/plain' },\n                         { waitForTrailers: true });\n  stream.on('wantTrailers', () => {\n    stream.sendTrailers({ ABC: 'some value to send' });\n  });\n});\n
" } ], "properties": [ { "textRaw": "`headersSent` {boolean}", "type": "boolean", "name": "headersSent", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

True if headers were sent, false otherwise (read-only).

" }, { "textRaw": "`pushAllowed` {boolean}", "type": "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.

" } ] }, { "textRaw": "Class: Http2Server", "type": "class", "name": "Http2Server", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

Instances of Http2Server are created using the http2.createServer()\nfunction. The Http2Server class is not exported directly by the http2\nmodule.

", "events": [ { "textRaw": "Event: 'checkContinue'", "type": "event", "name": "checkContinue", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "params": [ { "textRaw": "`request` {http2.Http2ServerRequest}", "name": "request", "type": "http2.Http2ServerRequest" }, { "textRaw": "`response` {http2.Http2ServerResponse}", "name": "response", "type": "http2.Http2ServerResponse" } ], "desc": "

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.

\n

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.

\n

Note that when this event is emitted and handled, the 'request' event will\nnot be emitted.

" }, { "textRaw": "Event: 'request'", "type": "event", "name": "request", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`request` {http2.Http2ServerRequest}", "name": "request", "type": "http2.Http2ServerRequest" }, { "textRaw": "`response` {http2.Http2ServerResponse}", "name": "response", "type": "http2.Http2ServerResponse" } ], "desc": "

Emitted each time there is a request. Note that there may be multiple requests\nper session. See the Compatibility API.

" }, { "textRaw": "Event: 'session'", "type": "event", "name": "session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'session' event is emitted when a new Http2Session is created by the\nHttp2Server.

" }, { "textRaw": "Event: 'sessionError'", "type": "event", "name": "sessionError", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'sessionError' event is emitted when an 'error' event is emitted by\nan Http2Session object associated with the Http2Server.

" }, { "textRaw": "Event: 'stream'", "type": "event", "name": "stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'stream' event is emitted when a 'stream' event has been emitted by\nan Http2Session associated with the server.

\n
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
" }, { "textRaw": "Event: 'timeout'", "type": "event", "name": "timeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'timeout' event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2server.setTimeout().\nDefault: 2 minutes.

" } ], "methods": [ { "textRaw": "server.close([callback])", "type": "method", "name": "close", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ] } ], "desc": "

Stops the server from accepting new connections. See net.Server.close().

\n

Note that this is not analogous to restricting new requests since HTTP/2\nconnections are persistent. To achieve a similar graceful shutdown behavior,\nconsider also using http2session.close() on active sessions.

" }, { "textRaw": "server.setTimeout([msecs][, callback])", "type": "method", "name": "setTimeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Http2Server}", "name": "return", "type": "Http2Server" }, "params": [ { "textRaw": "`msecs` {number} **Default:** `120000` (2 minutes)", "name": "msecs", "type": "number", "default": "`120000` (2 minutes)", "optional": true }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ] } ], "desc": "

Used to set the timeout value for http2 server requests,\nand sets a callback function that is called when there is no activity\non the Http2Server after msecs milliseconds.

\n

The given callback is registered as a listener on the 'timeout' event.

\n

In case of no callback function were assigned, a new ERR_INVALID_CALLBACK\nerror will be thrown.

" } ] }, { "textRaw": "Class: Http2SecureServer", "type": "class", "name": "Http2SecureServer", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

Instances of Http2SecureServer are created using the\nhttp2.createSecureServer() function. The Http2SecureServer class is not\nexported directly by the http2 module.

", "events": [ { "textRaw": "Event: 'checkContinue'", "type": "event", "name": "checkContinue", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "params": [ { "textRaw": "`request` {http2.Http2ServerRequest}", "name": "request", "type": "http2.Http2ServerRequest" }, { "textRaw": "`response` {http2.Http2ServerResponse}", "name": "response", "type": "http2.Http2ServerResponse" } ], "desc": "

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.

\n

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.

\n

Note that when this event is emitted and handled, the 'request' event will\nnot be emitted.

" }, { "textRaw": "Event: 'request'", "type": "event", "name": "request", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`request` {http2.Http2ServerRequest}", "name": "request", "type": "http2.Http2ServerRequest" }, { "textRaw": "`response` {http2.Http2ServerResponse}", "name": "response", "type": "http2.Http2ServerResponse" } ], "desc": "

Emitted each time there is a request. Note that there may be multiple requests\nper session. See the Compatibility API.

" }, { "textRaw": "Event: 'session'", "type": "event", "name": "session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'session' event is emitted when a new Http2Session is created by the\nHttp2SecureServer.

" }, { "textRaw": "Event: 'sessionError'", "type": "event", "name": "sessionError", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'sessionError' event is emitted when an 'error' event is emitted by\nan Http2Session object associated with the Http2SecureServer.

" }, { "textRaw": "Event: 'stream'", "type": "event", "name": "stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'stream' event is emitted when a 'stream' event has been emitted by\nan Http2Session associated with the server.

\n
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
" }, { "textRaw": "Event: 'timeout'", "type": "event", "name": "timeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'timeout' event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2secureServer.setTimeout().\nDefault: 2 minutes.

" }, { "textRaw": "Event: 'unknownProtocol'", "type": "event", "name": "unknownProtocol", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

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.

" } ], "methods": [ { "textRaw": "server.close([callback])", "type": "method", "name": "close", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ] } ], "desc": "

Stops the server from accepting new connections. See tls.Server.close().

\n

Note that this is not analogous to restricting new requests since HTTP/2\nconnections are persistent. To achieve a similar graceful shutdown behavior,\nconsider also using http2session.close() on active sessions.

" }, { "textRaw": "server.setTimeout([msecs][, callback])", "type": "method", "name": "setTimeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Http2SecureServer}", "name": "return", "type": "Http2SecureServer" }, "params": [ { "textRaw": "`msecs` {number} **Default:** `120000` (2 minutes)", "name": "msecs", "type": "number", "default": "`120000` (2 minutes)", "optional": true }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ] } ], "desc": "

Used to set the timeout value for http2 secure server requests,\nand sets a callback function that is called when there is no activity\non the Http2SecureServer after msecs milliseconds.

\n

The given callback is registered as a listener on the 'timeout' event.

\n

In case of no callback function were assigned, a new ERR_INVALID_CALLBACK\nerror will be thrown.

" } ] } ], "methods": [ { "textRaw": "http2.createServer(options[, onRequestHandler])", "type": "method", "name": "createServer", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v8.9.3", "pr-url": "https://github.com/nodejs/node/pull/17105", "description": "Added the `maxOutstandingPings` option with a default limit of 10." }, { "version": "v8.9.3", "pr-url": "https://github.com/nodejs/node/pull/16676", "description": "Added the `maxHeaderListPairs` option with a default limit of 128 header pairs." }, { "version": "v9.6.0", "pr-url": "https://github.com/nodejs/node/pull/15752", "description": "Added the `Http1IncomingMessage` and `Http1ServerResponse` option." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Http2Server}", "name": "return", "type": "Http2Server" }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size for deflating header fields. **Default:** `4Kib`.", "name": "maxDeflateDynamicTableSize", "type": "number", "default": "`4Kib`", "desc": "Sets the maximum dynamic table size for deflating header fields." }, { "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`. 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. **Default:** `10`.", "name": "maxSessionMemory", "type": "number", "default": "`10`", "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`. 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. The minimum value is `4`. **Default:** `128`.", "name": "maxHeaderListPairs", "type": "number", "default": "`128`", "desc": "Sets the maximum number of header entries. The minimum value is `4`." }, { "textRaw": "`maxOutstandingPings` {number} Sets the maximum number of outstanding, unacknowledged pings. **Default:** `10`.", "name": "maxOutstandingPings", "type": "number", "default": "`10`", "desc": "Sets the maximum number of outstanding, unacknowledged pings." }, { "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:", "name": "paddingStrategy", "type": "number", "default": "`http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", "desc": "Identifies the strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames.", "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." } ] }, { "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", "default": "`100`", "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`." }, { "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": "`Http1IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage` class to used for HTTP/1 fallback. Useful for extending the original `http.IncomingMessage`. **Default:** `http.IncomingMessage`.", "name": "Http1IncomingMessage", "type": "http.IncomingMessage", "default": "`http.IncomingMessage`", "desc": "Specifies the `IncomingMessage` class to used for HTTP/1 fallback. Useful for extending the original `http.IncomingMessage`." }, { "textRaw": "`Http1ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class to used for HTTP/1 fallback. Useful for extending the original `http.ServerResponse`. **Default:** `http.ServerResponse`.", "name": "Http1ServerResponse", "type": "http.ServerResponse", "default": "`http.ServerResponse`", "desc": "Specifies the `ServerResponse` class to used for HTTP/1 fallback. Useful for extending the original `http.ServerResponse`." }, { "textRaw": "`Http2ServerRequest` {http2.Http2ServerRequest} Specifies the `Http2ServerRequest` class to use. Useful for extending the original `Http2ServerRequest`. **Default:** `Http2ServerRequest`.", "name": "Http2ServerRequest", "type": "http2.Http2ServerRequest", "default": "`Http2ServerRequest`", "desc": "Specifies the `Http2ServerRequest` class to use. Useful for extending the original `Http2ServerRequest`." }, { "textRaw": "`Http2ServerResponse` {http2.Http2ServerResponse} Specifies the `Http2ServerResponse` class to use. Useful for extending the original `Http2ServerResponse`. **Default:** `Http2ServerResponse`.", "name": "Http2ServerResponse", "type": "http2.Http2ServerResponse", "default": "`Http2ServerResponse`", "desc": "Specifies the `Http2ServerResponse` class to use. Useful for extending the original `Http2ServerResponse`." } ] }, { "textRaw": "`onRequestHandler` {Function} See [Compatibility API][]", "name": "onRequestHandler", "type": "Function", "desc": "See [Compatibility API][]", "optional": true } ] } ], "desc": "

Returns a net.Server instance that creates and manages Http2Session\ninstances.

\n

Since there are no browsers known that support\nunencrypted HTTP/2, the use of\nhttp2.createSecureServer() is necessary when communicating\nwith browser clients.

\n
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
" }, { "textRaw": "http2.createSecureServer(options[, onRequestHandler])", "type": "method", "name": "createSecureServer", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v10.12.0", "pr-url": "https://github.com/nodejs/node/pull/22956", "description": "Added the `origins` option to automatically send an `ORIGIN` frame on `Http2Session` startup." }, { "version": "v8.9.3", "pr-url": "https://github.com/nodejs/node/pull/17105", "description": "Added the `maxOutstandingPings` option with a default limit of 10." }, { "version": "v8.9.3", "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}", "name": "options", "type": "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`. See the [`'unknownProtocol'`][] event. See [ALPN negotiation][]. **Default:** `false`.", "name": "allowHTTP1", "type": "boolean", "default": "`false`", "desc": "Incoming client connections that do not support HTTP/2 will be downgraded to HTTP/1.x when set to `true`. 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", "default": "`4Kib`", "desc": "Sets the maximum dynamic table size for deflating header fields." }, { "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`. 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. **Default:** `10`.", "name": "maxSessionMemory", "type": "number", "default": "`10`", "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`. 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. The minimum value is `4`. **Default:** `128`.", "name": "maxHeaderListPairs", "type": "number", "default": "`128`", "desc": "Sets the maximum number of header entries. The minimum value is `4`." }, { "textRaw": "`maxOutstandingPings` {number} Sets the maximum number of outstanding, unacknowledged pings. **Default:** `10`.", "name": "maxOutstandingPings", "type": "number", "default": "`10`", "desc": "Sets the maximum number of outstanding, unacknowledged pings." }, { "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:", "name": "paddingStrategy", "type": "number", "default": "`http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", "desc": "Identifies the strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames.", "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." } ] }, { "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", "default": "`100`", "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`." }, { "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." }, { "textRaw": "`origins` {string[]} An array of origin strings to send within an `ORIGIN` frame immediately following creation of a new server `Http2Session`.", "name": "origins", "type": "string[]", "desc": "An array of origin strings to send within an `ORIGIN` frame immediately following creation of a new server `Http2Session`." } ] }, { "textRaw": "`onRequestHandler` {Function} See [Compatibility API][]", "name": "onRequestHandler", "type": "Function", "desc": "See [Compatibility API][]", "optional": true } ] } ], "desc": "

Returns a tls.Server instance that creates and manages Http2Session\ninstances.

\n
const http2 = require('http2');\nconst fs = require('fs');\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
" }, { "textRaw": "http2.connect(authority[, options][, listener])", "type": "method", "name": "connect", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v8.9.3", "pr-url": "https://github.com/nodejs/node/pull/17105", "description": "Added the `maxOutstandingPings` option with a default limit of 10." }, { "version": "v8.9.3", "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}", "name": "options", "type": "Object", "options": [ { "textRaw": "`maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size for deflating header fields. **Default:** `4Kib`.", "name": "maxDeflateDynamicTableSize", "type": "number", "default": "`4Kib`", "desc": "Sets the maximum dynamic table size for deflating header fields." }, { "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`. 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. **Default:** `10`.", "name": "maxSessionMemory", "type": "number", "default": "`10`", "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`. 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. The minimum value is `1`. **Default:** `128`.", "name": "maxHeaderListPairs", "type": "number", "default": "`128`", "desc": "Sets the maximum number of header entries. The minimum value is `1`." }, { "textRaw": "`maxOutstandingPings` {number} Sets the maximum number of outstanding, unacknowledged pings. **Default:** `10`.", "name": "maxOutstandingPings", "type": "number", "default": "`10`", "desc": "Sets the maximum number of outstanding, unacknowledged pings." }, { "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:", "name": "paddingStrategy", "type": "number", "default": "`http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", "desc": "Identifies the strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames.", "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." } ] }, { "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", "default": "`100`", "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`." }, { "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." } ], "optional": true }, { "textRaw": "`listener` {Function}", "name": "listener", "type": "Function", "optional": true } ] } ], "desc": "

Returns a ClientHttp2Session instance.

\n
const http2 = require('http2');\nconst client = http2.connect('https://localhost:1234');\n\n/* Use the client */\n\nclient.close();\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": [] } ], "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.

" }, { "textRaw": "http2.getPackedSettings(settings)", "type": "method", "name": "getPackedSettings", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "params": [ { "textRaw": "`settings` {HTTP/2 Settings Object}", "name": "settings", "type": "HTTP/2 Settings Object" } ] } ], "desc": "

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.

\n
const http2 = require('http2');\n\nconst packed = http2.getPackedSettings({ enablePush: false });\n\nconsole.log(packed.toString('base64'));\n// Prints: AAIAAAAA\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." } ] } ], "desc": "

Returns a HTTP/2 Settings Object containing the deserialized settings from\nthe given Buffer as generated by http2.getPackedSettings().

" } ], "properties": [ { "textRaw": "http2.constants", "name": "constants", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "modules": [ { "textRaw": "Error Codes for RST_STREAM and GOAWAY", "name": "error_codes_for_rst_stream_and_goaway", "desc": "

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ValueNameConstant
0x00No Errorhttp2.constants.NGHTTP2_NO_ERROR
0x01Protocol Errorhttp2.constants.NGHTTP2_PROTOCOL_ERROR
0x02Internal Errorhttp2.constants.NGHTTP2_INTERNAL_ERROR
0x03Flow Control Errorhttp2.constants.NGHTTP2_FLOW_CONTROL_ERROR
0x04Settings Timeouthttp2.constants.NGHTTP2_SETTINGS_TIMEOUT
0x05Stream Closedhttp2.constants.NGHTTP2_STREAM_CLOSED
0x06Frame Size Errorhttp2.constants.NGHTTP2_FRAME_SIZE_ERROR
0x07Refused Streamhttp2.constants.NGHTTP2_REFUSED_STREAM
0x08Cancelhttp2.constants.NGHTTP2_CANCEL
0x09Compression Errorhttp2.constants.NGHTTP2_COMPRESSION_ERROR
0x0aConnect Errorhttp2.constants.NGHTTP2_CONNECT_ERROR
0x0bEnhance Your Calmhttp2.constants.NGHTTP2_ENHANCE_YOUR_CALM
0x0cInadequate Securityhttp2.constants.NGHTTP2_INADEQUATE_SECURITY
0x0dHTTP/1.1 Requiredhttp2.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().

", "type": "module", "displayName": "Error Codes for RST_STREAM and GOAWAY" } ] } ], "type": "module", "displayName": "Core API" }, { "textRaw": "Compatibility API", "name": "compatibility_api", "desc": "

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.

\n

The following example creates an HTTP/2 server using the compatibility\nAPI:

\n
const 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
\n

In 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.

\n

The 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.

", "modules": [ { "textRaw": "ALPN negotiation", "name": "alpn_negotiation", "desc": "

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.

\n

The following example creates a server that supports both protocols:

\n
const { 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
\n

The 'request' event works identically on both HTTPS and\nHTTP/2.

", "type": "module", "displayName": "ALPN negotiation" } ], "classes": [ { "textRaw": "Class: http2.Http2ServerRequest", "type": "class", "name": "http2.Http2ServerRequest", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

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.

\n

It implements the Readable Stream interface, as well as the\nfollowing additional events, methods, and properties.

", "events": [ { "textRaw": "Event: 'aborted'", "type": "event", "name": "aborted", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'aborted' event is emitted whenever a Http2ServerRequest instance is\nabnormally aborted in mid-communication.

\n

The 'aborted' event will only be emitted if the Http2ServerRequest writable\nside has not been ended.

" }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

Indicates that the underlying Http2Stream was closed.\nJust like 'end', this event occurs only once per response.

" } ], "properties": [ { "textRaw": "`aborted` {boolean}", "type": "boolean", "name": "aborted", "meta": { "added": [ "v10.1.0" ], "changes": [] }, "desc": "

The request.aborted property will be true if the request has\nbeen aborted.

" }, { "textRaw": "`headers` {Object}", "type": "Object", "name": "headers", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The request/response headers object.

\n

Key-value pairs of header names and values. Header names are lower-cased.

\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

See HTTP/2 Headers Object.

\n

In 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:

\n
removeAllHeaders(request.headers);\nassert(request.url);   // Fails because the :path header has been removed\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'.

\n

Also message.httpVersionMajor is the first integer and\nmessage.httpVersionMinor is the second.

" }, { "textRaw": "`method` {string}", "type": "string", "name": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The request method as a string. Read-only. Examples: 'GET', 'DELETE'.

" }, { "textRaw": "`rawHeaders` {string[]}", "type": "string[]", "name": "rawHeaders", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The raw request/response headers list exactly as they were received.

\n

Note 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.

\n

Header 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
" }, { "textRaw": "`rawTrailers` {string[]}", "type": "string[]", "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.

" }, { "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.

\n

destroyed, readable, and writable properties will be retrieved from and\nset on request.stream.

\n

destroy, emit, end, on and once methods will be called on\nrequest.stream.

\n

setTimeout method will be called on request.stream.session.

\n

pause, read, resume, and write will throw an error with code\nERR_HTTP2_NO_SOCKET_MANIPULATION. See Http2Session and Sockets for\nmore information.

\n

All other interactions will be routed directly to the socket. With TLS support,\nuse request.socket.getPeerCertificate() to obtain the client's\nauthentication details.

" }, { "textRaw": "`stream` {Http2Stream}", "type": "Http2Stream", "name": "stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The Http2Stream object backing the request.

" }, { "textRaw": "`trailers` {Object}", "type": "Object", "name": "trailers", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The request/response trailers object. Only populated at the 'end' event.

" }, { "textRaw": "`url` {string}", "type": "string", "name": "url", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Request URL string. This contains only the URL that is\npresent in the actual HTTP request. If the request is:

\n
GET /status?name=ryan HTTP/1.1\\r\\n\nAccept: text/plain\\r\\n\n\\r\\n\n
\n

Then request.url will be:

\n\n
'/status?name=ryan'\n
\n

To parse the url into its parts require('url').parse(request.url)\ncan be used:

\n
$ 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
\n

To 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.

\n
$ 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
" } ], "methods": [ { "textRaw": "request.destroy([error])", "type": "method", "name": "destroy", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`error` {Error}", "name": "error", "type": "Error", "optional": true } ] } ], "desc": "

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.

\n

It does nothing if the stream was already destroyed.

" }, { "textRaw": "request.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {http2.Http2ServerRequest}", "name": "return", "type": "http2.Http2ServerRequest" }, "params": [ { "textRaw": "`msecs` {number}", "name": "msecs", "type": "number" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "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.

\n

If no 'timeout' listener is added to the request, the response, or\nthe server, then Http2Streams 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.

" } ] }, { "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.

\n

The response inherits from Stream, and additionally implements the\nfollowing:

", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

Indicates that the underlying Http2Stream was terminated before\nresponse.end() was called or able to flush.

" }, { "textRaw": "Event: 'finish'", "type": "event", "name": "finish", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

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.

\n

After this event, no more events will be emitted on the response object.

" } ], "methods": [ { "textRaw": "response.addTrailers(headers)", "type": "method", "name": "addTrailers", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {Object}", "name": "headers", "type": "Object" } ] } ], "desc": "

This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.

\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

" }, { "textRaw": "response.end([data][, encoding][, callback])", "type": "method", "name": "end", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18780", "description": "This method now returns a reference to `ServerResponse`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`data` {string|Buffer}", "name": "data", "type": "string|Buffer", "optional": true }, { "textRaw": "`encoding` {string}", "name": "encoding", "type": "string", "optional": true }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ] } ], "desc": "

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.

\n

If data is specified, it is equivalent to calling\nresponse.write(data, encoding) followed by response.end(callback).

\n

If callback is specified, it will be called when the response stream\nis finished.

" }, { "textRaw": "response.getHeader(name)", "type": "method", "name": "getHeader", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "

Reads out a header that has already been queued but not sent to the client.\nNote that the name is case insensitive.

\n
const contentType = response.getHeader('content-type');\n
" }, { "textRaw": "response.getHeaderNames()", "type": "method", "name": "getHeaderNames", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string[]}", "name": "return", "type": "string[]" }, "params": [] } ], "desc": "

Returns an array containing the unique names of the current outgoing headers.\nAll header names are lowercase.

\n
response.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headerNames = response.getHeaderNames();\n// headerNames === ['foo', 'set-cookie']\n
" }, { "textRaw": "response.getHeaders()", "type": "method", "name": "getHeaders", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "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.

\n

The 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.

\n
response.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
" }, { "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" } ] } ], "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.

\n
const hasContentType = response.hasHeader('content-type');\n
" }, { "textRaw": "response.removeHeader(name)", "type": "method", "name": "removeHeader", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "

Removes a header that has been queued for implicit sending.

\n
response.removeHeader('Content-Encoding');\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[]" } ] } ], "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.

\n
response.setHeader('Content-Type', 'text/html');\n
\n

or

\n
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\n
\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

\n

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.

\n
// 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
" }, { "textRaw": "response.setTimeout(msecs[, callback])", "type": "method", "name": "setTimeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {http2.Http2ServerResponse}", "name": "return", "type": "http2.Http2ServerResponse" }, "params": [ { "textRaw": "`msecs` {number}", "name": "msecs", "type": "number" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "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.

\n

If no 'timeout' listener is added to the request, the response, or\nthe server, then Http2Streams 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.

" }, { "textRaw": "response.write(chunk[, encoding][, callback])", "type": "method", "name": "write", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`chunk` {string|Buffer}", "name": "chunk", "type": "string|Buffer" }, { "textRaw": "`encoding` {string}", "name": "encoding", "type": "string", "optional": true }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ] } ], "desc": "

If this method is called and response.writeHead() has not been called,\nit will switch to implicit header mode and flush the implicit headers.

\n

This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.

\n

Note 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.

\n

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.

\n

This is the raw HTTP body and has nothing to do with higher-level multi-part\nbody encodings that may be used.

\n

The 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.

\n

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.

" }, { "textRaw": "response.writeContinue()", "type": "method", "name": "writeContinue", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Sends a status 100 Continue to the client, indicating that the request body\nshould be sent. See the 'checkContinue' event on Http2Server and\nHttp2SecureServer.

" }, { "textRaw": "response.writeHead(statusCode[, statusMessage][, headers])", "type": "method", "name": "writeHead", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`statusCode` {number}", "name": "statusCode", "type": "number" }, { "textRaw": "`statusMessage` {string}", "name": "statusMessage", "type": "string", "optional": true }, { "textRaw": "`headers` {Object}", "name": "headers", "type": "Object", "optional": true } ] } ], "desc": "

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.

\n

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.

\n
const body = 'hello world';\nresponse.writeHead(200, {\n  'Content-Length': Buffer.byteLength(body),\n  'Content-Type': 'text/plain' });\n
\n

Note 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.

\n

This method may be called at most one time on a message before\nresponse.end() is called.

\n

If response.write() or response.end() are called before calling\nthis, the implicit/mutable headers will be calculated and call this function.

\n

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.

\n
// 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

Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

" }, { "textRaw": "response.createPushResponse(headers, callback)", "type": "method", "name": "createPushResponse", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object} An object describing the headers", "name": "headers", "type": "HTTP/2 Headers Object", "desc": "An object describing the headers" }, { "textRaw": "`callback` {Function} Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method", "name": "callback", "type": "Function", "desc": "Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`stream` {ServerHttp2Stream} The newly-created `ServerHttp2Stream` object", "name": "stream", "type": "ServerHttp2Stream", "desc": "The newly-created `ServerHttp2Stream` object" } ] } ] } ], "desc": "

Call http2stream.pushStream() with the given headers, and wrap the\ngiven Http2Stream on a newly created Http2ServerResponse as the callback\nparameter if successful. When Http2ServerRequest is closed, the callback is\ncalled with an error ERR_HTTP2_INVALID_STREAM.

" } ], "properties": [ { "textRaw": "`connection` {net.Socket|tls.TLSSocket}", "type": "net.Socket|tls.TLSSocket", "name": "connection", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

See response.socket.

" }, { "textRaw": "`finished` {boolean}", "type": "boolean", "name": "finished", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Boolean value that indicates whether the response has completed. Starts\nas false. After response.end() executes, the value will be true.

" }, { "textRaw": "`headersSent` {boolean}", "type": "boolean", "name": "headersSent", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

True if headers were sent, false otherwise (read-only).

" }, { "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.

\n

This should only be disabled for testing; HTTP requires the Date header\nin responses.

" }, { "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.

\n

destroyed, readable, and writable properties will be retrieved from and\nset on response.stream.

\n

destroy, emit, end, on and once methods will be called on\nresponse.stream.

\n

setTimeout method will be called on response.stream.session.

\n

pause, read, resume, and write will throw an error with code\nERR_HTTP2_NO_SOCKET_MANIPULATION. See Http2Session and Sockets for\nmore information.

\n

All other interactions will be routed directly to the socket.

\n
const 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
" }, { "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.

\n
response.statusCode = 404;\n
\n

After response header was sent to the client, this property indicates the\nstatus code which was sent out.

" }, { "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.

" }, { "textRaw": "`stream` {Http2Stream}", "type": "Http2Stream", "name": "stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The Http2Stream object backing the response.

" } ] } ], "type": "module", "displayName": "Compatibility API" }, { "textRaw": "Collecting HTTP/2 Performance Metrics", "name": "collecting_http/2_performance_metrics", "desc": "

The Performance Observer API can be used to collect basic performance\nmetrics for each Http2Session and Http2Stream instance.

\n
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
\n

The entryType property of the PerformanceEntry will be equal to 'http2'.

\n

The name property of the PerformanceEntry will be equal to either\n'Http2Stream' or 'Http2Session'.

\n

If name is equal to Http2Stream, the PerformanceEntry will contain the\nfollowing additional properties:

\n\n

If name is equal to Http2Session, the PerformanceEntry will contain the\nfollowing additional properties:

\n", "type": "module", "displayName": "Collecting HTTP/2 Performance Metrics" } ], "type": "module", "displayName": "HTTP/2" } ] }