/
opt
/
alt
/
alt-nodejs10
/
root
/
lib
/
node_modules
/
npm
/
html
/
html
/
api
/
Upload Filee
HOME
{ "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": "<p>The <code>http2</code> module provides an implementation of the <a href=\"https://tools.ietf.org/html/rfc7540\">HTTP/2</a> protocol. It\ncan be accessed using:</p>\n<pre><code class=\"language-js\">const http2 = require('http2');\n</code></pre>", "modules": [ { "textRaw": "Core API", "name": "core_api", "desc": "<p>The Core API provides a low-level interface designed specifically around\nsupport for HTTP/2 protocol features. It is specifically <em>not</em> designed for\ncompatibility with the existing <a href=\"http.html\">HTTP/1</a> module API. However,\nthe <a href=\"#http2_compatibility_api\">Compatibility API</a> is.</p>\n<p>The <code>http2</code> Core API is much more symmetric between client and server than the\n<code>http</code> API. For instance, most events, like <code>'error'</code>, <code>'connect'</code> and\n<code>'stream'</code>, can be emitted either by client-side code or server-side code.</p>", "modules": [ { "textRaw": "Server-side example", "name": "server-side_example", "desc": "<p>The following illustrates a simple HTTP/2 server using the Core API.\nSince there are no browsers known that support\n<a href=\"https://http2.github.io/faq/#does-http2-require-encryption\">unencrypted HTTP/2</a>, the use of\n<a href=\"#http2_http2_createsecureserver_options_onrequesthandler\"><code>http2.createSecureServer()</code></a> is necessary when communicating\nwith browser clients.</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>To generate the certificate and key for this example, run:</p>\n<pre><code class=\"language-bash\">openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \\\n -keyout localhost-privkey.pem -out localhost-cert.pem\n</code></pre>", "type": "module", "displayName": "Server-side example" }, { "textRaw": "Client-side example", "name": "client-side_example", "desc": "<p>The following illustrates an HTTP/2 client:</p>\n<pre><code class=\"language-js\">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</code></pre>", "type": "module", "displayName": "Client-side example" }, { "textRaw": "Headers Object", "name": "headers_object", "desc": "<p>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 <code>Array</code> of strings (in order\nto send more than one value per header field).</p>\n<pre><code class=\"language-js\">const headers = {\n ':status': '200',\n 'content-type': 'text-plain',\n 'ABC': ['has', 'more', 'than', 'one', 'value']\n};\n\nstream.respond(headers);\n</code></pre>\n<p>Header objects passed to callback functions will have a <code>null</code> prototype. This\nmeans that normal JavaScript object methods such as\n<code>Object.prototype.toString()</code> and <code>Object.prototype.hasOwnProperty()</code> will\nnot work.</p>\n<p>For incoming headers:</p>\n<ul>\n<li>The <code>:status</code> header is converted to <code>number</code>.</li>\n<li>Duplicates of <code>:status</code>, <code>:method</code>, <code>:authority</code>, <code>:scheme</code>, <code>:path</code>,\n<code>:protocol</code>, <code>age</code>, <code>authorization</code>, <code>access-control-allow-credentials</code>,\n<code>access-control-max-age</code>, <code>access-control-request-method</code>, <code>content-encoding</code>,\n<code>content-language</code>, <code>content-length</code>, <code>content-location</code>, <code>content-md5</code>,\n<code>content-range</code>, <code>content-type</code>, <code>date</code>, <code>dnt</code>, <code>etag</code>, <code>expires</code>, <code>from</code>,\n<code>if-match</code>, <code>if-modified-since</code>, <code>if-none-match</code>, <code>if-range</code>,\n<code>if-unmodified-since</code>, <code>last-modified</code>, <code>location</code>, <code>max-forwards</code>,\n<code>proxy-authorization</code>, <code>range</code>, <code>referer</code>,<code>retry-after</code>, <code>tk</code>,\n<code>upgrade-insecure-requests</code>, <code>user-agent</code> or <code>x-content-type-options</code> are\ndiscarded.</li>\n<li><code>set-cookie</code> is always an array. Duplicates are added to the array.</li>\n<li>For duplicate <code>cookie</code> headers, the values are joined together with '; '.</li>\n<li>For all other headers, the values are joined together with ', '.</li>\n</ul>\n<pre><code class=\"language-js\">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</code></pre>", "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": "<p>The <code>http2.getDefaultSettings()</code>, <code>http2.getPackedSettings()</code>,\n<code>http2.createServer()</code>, <code>http2.createSecureServer()</code>,\n<code>http2session.settings()</code>, <code>http2session.localSettings</code>, and\n<code>http2session.remoteSettings</code> APIs either return or receive as input an\nobject that defines configuration settings for an <code>Http2Session</code> object.\nThese objects are ordinary JavaScript objects containing the following\nproperties.</p>\n<ul>\n<li><code>headerTableSize</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> Specifies the maximum number of bytes used for\nheader compression. The minimum allowed value is 0. The maximum allowed value\nis 2<sup>32</sup>-1. <strong>Default:</strong> <code>4,096 octets</code>.</li>\n<li><code>enablePush</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type\" class=\"type\"><boolean></a> Specifies <code>true</code> if HTTP/2 Push Streams are to be\npermitted on the <code>Http2Session</code> instances.</li>\n<li><code>initialWindowSize</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> Specifies the <em>senders</em> initial window size\nfor stream-level flow control. The minimum allowed value is 0. The maximum\nallowed value is 2<sup>32</sup>-1. <strong>Default:</strong> <code>65,535 bytes</code>.</li>\n<li><code>maxFrameSize</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> Specifies the size of the largest frame payload.\nThe minimum allowed value is 16,384. The maximum allowed value\nis 2<sup>24</sup>-1. <strong>Default:</strong> <code>16,384 bytes</code>.</li>\n<li><code>maxConcurrentStreams</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> Specifies the maximum number of concurrent\nstreams permitted on an <code>Http2Session</code>. There is no default value which\nimplies, at least theoretically, 2<sup>31</sup>-1 streams may be open\nconcurrently at any given time in an <code>Http2Session</code>. The minimum value\nis 0. The maximum allowed value is 2<sup>31</sup>-1.</li>\n<li><code>maxHeaderListSize</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> Specifies the maximum size (uncompressed octets)\nof header list that will be accepted. The minimum allowed value is 0. The\nmaximum allowed value is 2<sup>32</sup>-1. <strong>Default:</strong> <code>65535</code>.</li>\n<li><code>enableConnectProtocol</code><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type\" class=\"type\"><boolean></a> Specifies <code>true</code> if the \"Extended Connect\nProtocol\" defined by <a href=\"https://tools.ietf.org/html/rfc8441\">RFC 8441</a> is to be enabled. This setting is only\nmeaningful if sent by the server. Once the <code>enableConnectProtocol</code> setting\nhas been enabled for a given <code>Http2Session</code>, it cannot be disabled.</li>\n</ul>\n<p>All additional properties on the settings object are ignored.</p>", "type": "module", "displayName": "Settings Object" }, { "textRaw": "Using `options.selectPadding()`", "name": "using_`options.selectpadding()`", "desc": "<p>When <code>options.paddingStrategy</code> is equal to\n<code>http2.constants.PADDING_STRATEGY_CALLBACK</code>, the HTTP/2 implementation will\nconsult the <code>options.selectPadding()</code> callback function, if provided, to\ndetermine the specific amount of padding to use per <code>HEADERS</code> and <code>DATA</code> frame.</p>\n<p>The <code>options.selectPadding()</code> function receives two numeric arguments,\n<code>frameLen</code> and <code>maxFrameLen</code> and must return a number <code>N</code> such that\n<code>frameLen <= N <= maxFrameLen</code>.</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>The <code>options.selectPadding()</code> function is invoked once for <em>every</em> <code>HEADERS</code> and\n<code>DATA</code> frame. This has a definite noticeable impact on performance.</p>", "type": "module", "displayName": "Using `options.selectPadding()`" }, { "textRaw": "Error Handling", "name": "error_handling", "desc": "<p>There are several types of error conditions that may arise when using the\n<code>http2</code> module:</p>\n<p>Validation errors occur when an incorrect argument, option, or setting value is\npassed in. These will always be reported by a synchronous <code>throw</code>.</p>\n<p>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 <code>throw</code> or via an <code>'error'</code> event on\nthe <code>Http2Stream</code>, <code>Http2Session</code> or HTTP/2 Server objects, depending on where\nand when the error occurs.</p>\n<p>Internal errors occur when an HTTP/2 session fails unexpectedly. These will be\nreported via an <code>'error'</code> event on the <code>Http2Session</code> or HTTP/2 Server objects.</p>\n<p>Protocol errors occur when various HTTP/2 protocol constraints are violated.\nThese will be reported using either a synchronous <code>throw</code> or via an <code>'error'</code>\nevent on the <code>Http2Stream</code>, <code>Http2Session</code> or HTTP/2 Server objects, depending\non where and when the error occurs.</p>", "type": "module", "displayName": "Error Handling" }, { "textRaw": "Invalid character handling in header names and values", "name": "invalid_character_handling_in_header_names_and_values", "desc": "<p>The HTTP/2 implementation applies stricter handling of invalid characters in\nHTTP header names and values than the HTTP/1 implementation.</p>\n<p>Header field names are <em>case-insensitive</em> 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. <code>Content-Type</code>) but will convert\nthose to lower-case (e.g. <code>content-type</code>) upon transmission.</p>\n<p>Header field-names <em>must only</em> contain one or more of the following ASCII\ncharacters: <code>a</code>-<code>z</code>, <code>A</code>-<code>Z</code>, <code>0</code>-<code>9</code>, <code>!</code>, <code>#</code>, <code>$</code>, <code>%</code>, <code>&</code>, <code>'</code>, <code>*</code>, <code>+</code>,\n<code>-</code>, <code>.</code>, <code>^</code>, <code>_</code>, <code>`</code> (backtick), <code>|</code>, and <code>~</code>.</p>\n<p>Using invalid characters within an HTTP header field name will cause the\nstream to be closed with a protocol error being reported.</p>\n<p>Header field values are handled with more leniency but <em>should</em> not contain\nnew-line or carriage return characters and <em>should</em> be limited to US-ASCII\ncharacters, per the requirements of the HTTP specification.</p>", "type": "module", "displayName": "Invalid character handling in header names and values" }, { "textRaw": "Push streams on the client", "name": "push_streams_on_the_client", "desc": "<p>To receive pushed streams on the client, set a listener for the <code>'stream'</code>\nevent on the <code>ClientHttp2Session</code>:</p>\n<pre><code class=\"language-js\">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</code></pre>", "type": "module", "displayName": "Push streams on the client" }, { "textRaw": "Supporting the CONNECT method", "name": "supporting_the_connect_method", "desc": "<p>The <code>CONNECT</code> method is used to allow an HTTP/2 server to be used as a proxy\nfor TCP/IP connections.</p>\n<p>A simple TCP Server:</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>An HTTP/2 CONNECT proxy:</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>An HTTP/2 CONNECT client:</p>\n<pre><code class=\"language-js\">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</code></pre>", "type": "module", "displayName": "Supporting the CONNECT method" }, { "textRaw": "The Extended CONNECT Protocol", "name": "the_extended_connect_protocol", "desc": "<p><a href=\"https://tools.ietf.org/html/rfc8441\">RFC 8441</a> defines an \"Extended CONNECT Protocol\" extension to HTTP/2 that\nmay be used to bootstrap the use of an <code>Http2Stream</code> using the <code>CONNECT</code>\nmethod as a tunnel for other communication protocols (such as WebSockets).</p>\n<p>The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using\nthe <code>enableConnectProtocol</code> setting:</p>\n<pre><code class=\"language-js\">const http2 = require('http2');\nconst settings = { enableConnectProtocol: true };\nconst server = http2.createServer({ settings });\n</code></pre>\n<p>Once the client receives the <code>SETTINGS</code> frame from the server indicating that\nthe extended CONNECT may be used, it may send <code>CONNECT</code> requests that use the\n<code>':protocol'</code> HTTP/2 pseudo-header:</p>\n<pre><code class=\"language-js\">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</code></pre>", "type": "module", "displayName": "The Extended CONNECT Protocol" } ], "classes": [ { "textRaw": "Class: Http2Session", "type": "class", "name": "Http2Session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<ul>\n<li>Extends: <a href=\"events.html#events_class_eventemitter\" class=\"type\"><EventEmitter></a></li>\n</ul>\n<p>Instances of the <code>http2.Http2Session</code> class represent an active communications\nsession between an HTTP/2 client and server. Instances of this class are <em>not</em>\nintended to be constructed directly by user code.</p>\n<p>Each <code>Http2Session</code> instance will exhibit slightly different behaviors\ndepending on whether it is operating as a server or a client. The\n<code>http2session.type</code> property can be used to determine the mode in which an\n<code>Http2Session</code> is operating. On the server side, user code should rarely\nhave occasion to work with the <code>Http2Session</code> object directly, with most\nactions typically taken through interactions with either the <code>Http2Server</code> or\n<code>Http2Stream</code> objects.</p>\n<p>User code will not create <code>Http2Session</code> instances directly. Server-side\n<code>Http2Session</code> instances are created by the <code>Http2Server</code> instance when a\nnew HTTP/2 connection is received. Client-side <code>Http2Session</code> instances are\ncreated using the <code>http2.connect()</code> method.</p>", "modules": [ { "textRaw": "Http2Session and Sockets", "name": "http2session_and_sockets", "desc": "<p>Every <code>Http2Session</code> instance is associated with exactly one <a href=\"net.html#net_class_net_socket\"><code>net.Socket</code></a> or\n<a href=\"tls.html#tls_class_tls_tlssocket\"><code>tls.TLSSocket</code></a> when it is created. When either the <code>Socket</code> or the\n<code>Http2Session</code> are destroyed, both will be destroyed.</p>\n<p>Because 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 <code>Socket</code> instance bound to a <code>Http2Session</code>. Doing so can\nput the HTTP/2 session into an indeterminate state causing the session and\nthe socket to become unusable.</p>\n<p>Once a <code>Socket</code> has been bound to an <code>Http2Session</code>, user code should rely\nsolely on the API of the <code>Http2Session</code>.</p>", "type": "module", "displayName": "Http2Session and Sockets" } ], "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'close'</code> event is emitted once the <code>Http2Session</code> has been destroyed. Its\nlistener does not expect any arguments.</p>" }, { "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": "<p>The <code>'connect'</code> event is emitted once the <code>Http2Session</code> has been successfully\nconnected to the remote peer and communication may begin.</p>\n<p>User code will typically not listen for this event directly.</p>" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`error` {Error}", "name": "error", "type": "Error" } ], "desc": "<p>The <code>'error'</code> event is emitted when an error occurs during the processing of\nan <code>Http2Session</code>.</p>" }, { "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": "<p>The <code>'frameError'</code> 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 <code>Http2Stream</code>, an attempt to emit <code>'frameError'</code> event on the\n<code>Http2Stream</code> is made.</p>\n<p>If the <code>'frameError'</code> event is associated with a stream, the stream will be\nclosed and destroyed immediately following the <code>'frameError'</code> event. If the\nevent is not associated with a stream, the <code>Http2Session</code> will be shut down\nimmediately following the <code>'frameError'</code> event.</p>" }, { "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": "<p>The <code>'goaway'</code> event is emitted when a <code>GOAWAY</code> frame is received.</p>\n<p>The <code>Http2Session</code> instance will be shut down automatically when the <code>'goaway'</code>\nevent is emitted.</p>" }, { "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": "<p>The <code>'localSettings'</code> event is emitted when an acknowledgment <code>SETTINGS</code> frame\nhas been received.</p>\n<p>When using <code>http2session.settings()</code> to submit new settings, the modified\nsettings do not take effect until the <code>'localSettings'</code> event is emitted.</p>\n<pre><code class=\"language-js\">session.settings({ enablePush: false });\n\nsession.on('localSettings', (settings) => {\n /* Use the new settings */\n});\n</code></pre>" }, { "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": "<p>The <code>'ping'</code> event is emitted whenever a <code>PING</code> frame is received from the\nconnected peer.</p>" }, { "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": "<p>The <code>'remoteSettings'</code> event is emitted when a new <code>SETTINGS</code> frame is received\nfrom the connected peer.</p>\n<pre><code class=\"language-js\">session.on('remoteSettings', (settings) => {\n /* Use the new settings */\n});\n</code></pre>" }, { "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": "<p>The <code>'stream'</code> event is emitted when a new <code>Http2Stream</code> is created.</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>On the server side, user code will typically not listen for this event directly,\nand would instead register a handler for the <code>'stream'</code> event emitted by the\n<code>net.Server</code> or <code>tls.Server</code> instances returned by <code>http2.createServer()</code> and\n<code>http2.createSecureServer()</code>, respectively, as in the example below:</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>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.</p>" }, { "textRaw": "Event: 'timeout'", "type": "event", "name": "timeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>After the <code>http2session.setTimeout()</code> method is used to set the timeout period\nfor this <code>Http2Session</code>, the <code>'timeout'</code> event is emitted if there is no\nactivity on the <code>Http2Session</code> after the configured number of milliseconds.</p>\n<pre><code class=\"language-js\">session.setTimeout(2000);\nsession.on('timeout', () => { /* .. */ });\n</code></pre>" } ], "properties": [ { "textRaw": "`alpnProtocol` {string|undefined}", "type": "string|undefined", "name": "alpnProtocol", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "<p>Value will be <code>undefined</code> if the <code>Http2Session</code> is not yet connected to a\nsocket, <code>h2c</code> if the <code>Http2Session</code> is not connected to a <code>TLSSocket</code>, or\nwill return the value of the connected <code>TLSSocket</code>'s own <code>alpnProtocol</code>\nproperty.</p>" }, { "textRaw": "`closed` {boolean}", "type": "boolean", "name": "closed", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "<p>Will be <code>true</code> if this <code>Http2Session</code> instance has been closed, otherwise\n<code>false</code>.</p>" }, { "textRaw": "`connecting` {boolean}", "type": "boolean", "name": "connecting", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "desc": "<p>Will be <code>true</code> if this <code>Http2Session</code> instance is still connecting, will be set\nto <code>false</code> before emitting <code>connect</code> event and/or calling the <code>http2.connect</code>\ncallback.</p>" }, { "textRaw": "`destroyed` {boolean}", "type": "boolean", "name": "destroyed", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>Will be <code>true</code> if this <code>Http2Session</code> instance has been destroyed and must no\nlonger be used, otherwise <code>false</code>.</p>" }, { "textRaw": "`encrypted` {boolean|undefined}", "type": "boolean|undefined", "name": "encrypted", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "<p>Value is <code>undefined</code> if the <code>Http2Session</code> session socket has not yet been\nconnected, <code>true</code> if the <code>Http2Session</code> is connected with a <code>TLSSocket</code>,\nand <code>false</code> if the <code>Http2Session</code> is connected to any other kind of socket\nor stream.</p>" }, { "textRaw": "`localSettings` {HTTP/2 Settings Object}", "type": "HTTP/2 Settings Object", "name": "localSettings", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>A prototype-less object describing the current local settings of this\n<code>Http2Session</code>. The local settings are local to <em>this</em> <code>Http2Session</code> instance.</p>" }, { "textRaw": "`originSet` {string[]|undefined}", "type": "string[]|undefined", "name": "originSet", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "<p>If the <code>Http2Session</code> is connected to a <code>TLSSocket</code>, the <code>originSet</code> property\nwill return an <code>Array</code> of origins for which the <code>Http2Session</code> may be\nconsidered authoritative.</p>\n<p>The <code>originSet</code> property is only available when using a secure TLS connection.</p>" }, { "textRaw": "`pendingSettingsAck` {boolean}", "type": "boolean", "name": "pendingSettingsAck", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>Indicates whether or not the <code>Http2Session</code> is currently waiting for an\nacknowledgment for a sent <code>SETTINGS</code> frame. Will be <code>true</code> after calling the\n<code>http2session.settings()</code> method. Will be <code>false</code> once all sent SETTINGS\nframes have been acknowledged.</p>" }, { "textRaw": "`remoteSettings` {HTTP/2 Settings Object}", "type": "HTTP/2 Settings Object", "name": "remoteSettings", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>A prototype-less object describing the current remote settings of this\n<code>Http2Session</code>. The remote settings are set by the <em>connected</em> HTTP/2 peer.</p>" }, { "textRaw": "`socket` {net.Socket|tls.TLSSocket}", "type": "net.Socket|tls.TLSSocket", "name": "socket", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>Returns a <code>Proxy</code> object that acts as a <code>net.Socket</code> (or <code>tls.TLSSocket</code>) but\nlimits available methods to ones safe to use with HTTP/2.</p>\n<p><code>destroy</code>, <code>emit</code>, <code>end</code>, <code>pause</code>, <code>read</code>, <code>resume</code>, and <code>write</code> will throw\nan error with code <code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code>. See\n<a href=\"#http2_http2session_and_sockets\"><code>Http2Session</code> and Sockets</a> for more information.</p>\n<p><code>setTimeout</code> method will be called on this <code>Http2Session</code>.</p>\n<p>All other interactions will be routed directly to the socket.</p>" }, { "textRaw": "http2session.state", "name": "state", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>Provides miscellaneous information about the current state of the\n<code>Http2Session</code>.</p>\n<ul>\n<li>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" class=\"type\"><Object></a></p>\n<ul>\n<li><code>effectiveLocalWindowSize</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The current local (receive)\nflow control window size for the <code>Http2Session</code>.</li>\n<li><code>effectiveRecvDataLength</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The current number of bytes\nthat have been received since the last flow control <code>WINDOW_UPDATE</code>.</li>\n<li><code>nextStreamID</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The numeric identifier to be used the\nnext time a new <code>Http2Stream</code> is created by this <code>Http2Session</code>.</li>\n<li><code>localWindowSize</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The number of bytes that the remote peer can\nsend without receiving a <code>WINDOW_UPDATE</code>.</li>\n<li><code>lastProcStreamID</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The numeric id of the <code>Http2Stream</code>\nfor which a <code>HEADERS</code> or <code>DATA</code> frame was most recently received.</li>\n<li><code>remoteWindowSize</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The number of bytes that this <code>Http2Session</code>\nmay send without receiving a <code>WINDOW_UPDATE</code>.</li>\n<li><code>outboundQueueSize</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The number of frames currently within the\noutbound queue for this <code>Http2Session</code>.</li>\n<li><code>deflateDynamicTableSize</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The current size in bytes of the\noutbound header compression state table.</li>\n<li><code>inflateDynamicTableSize</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The current size in bytes of the\ninbound header compression state table.</li>\n</ul>\n</li>\n</ul>\n<p>An object describing the current status of this <code>Http2Session</code>.</p>" }, { "textRaw": "`type` {number}", "type": "number", "name": "type", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>The <code>http2session.type</code> will be equal to\n<code>http2.constants.NGHTTP2_SESSION_SERVER</code> if this <code>Http2Session</code> instance is a\nserver, and <code>http2.constants.NGHTTP2_SESSION_CLIENT</code> if the instance is a\nclient.</p>" } ], "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": "<p>Gracefully closes the <code>Http2Session</code>, allowing any existing streams to\ncomplete on their own and preventing new <code>Http2Stream</code> instances from being\ncreated. Once closed, <code>http2session.destroy()</code> <em>might</em> be called if there\nare no open <code>Http2Stream</code> instances.</p>\n<p>If specified, the <code>callback</code> function is registered as a handler for the\n<code>'close'</code> event.</p>" }, { "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": "<p>Immediately terminates the <code>Http2Session</code> and the associated <code>net.Socket</code> or\n<code>tls.TLSSocket</code>.</p>\n<p>Once destroyed, the <code>Http2Session</code> will emit the <code>'close'</code> event. If <code>error</code>\nis not undefined, an <code>'error'</code> event will be emitted immediately before the\n<code>'close'</code> event.</p>\n<p>If there are any remaining open <code>Http2Streams</code> associated with the\n<code>Http2Session</code>, those will also be destroyed.</p>" }, { "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": "<p>Transmits a <code>GOAWAY</code> frame to the connected peer <em>without</em> shutting down the\n<code>Http2Session</code>.</p>" }, { "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": "<p>Sends a <code>PING</code> frame to the connected HTTP/2 peer. A <code>callback</code> function must\nbe provided. The method will return <code>true</code> if the <code>PING</code> was sent, <code>false</code>\notherwise.</p>\n<p>The maximum number of outstanding (unacknowledged) pings is determined by the\n<code>maxOutstandingPings</code> configuration option. The default maximum is 10.</p>\n<p>If provided, the <code>payload</code> must be a <code>Buffer</code>, <code>TypedArray</code>, or <code>DataView</code>\ncontaining 8 bytes of data that will be transmitted with the <code>PING</code> and\nreturned with the ping acknowledgment.</p>\n<p>The callback will be invoked with three arguments: an error argument that will\nbe <code>null</code> if the <code>PING</code> was successfully acknowledged, a <code>duration</code> argument\nthat reports the number of milliseconds elapsed since the ping was sent and the\nacknowledgment was received, and a <code>Buffer</code> containing the 8-byte <code>PING</code>\npayload.</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>If the <code>payload</code> argument is not specified, the default payload will be the\n64-bit timestamp (little endian) marking the start of the <code>PING</code> duration.</p>" }, { "textRaw": "http2session.ref()", "type": "method", "name": "ref", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "<p>Calls <a href=\"net.html#net_socket_ref\"><code>ref()</code></a> on this <code>Http2Session</code>\ninstance's underlying <a href=\"net.html#net_class_net_socket\"><code>net.Socket</code></a>.</p>" }, { "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": "<p>Used to set a callback function that is called when there is no activity on\nthe <code>Http2Session</code> after <code>msecs</code> milliseconds. The given <code>callback</code> is\nregistered as a listener on the <code>'timeout'</code> event.</p>" }, { "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": "<p>Updates the current local settings for this <code>Http2Session</code> and sends a new\n<code>SETTINGS</code> frame to the connected HTTP/2 peer.</p>\n<p>Once called, the <code>http2session.pendingSettingsAck</code> property will be <code>true</code>\nwhile the session is waiting for the remote peer to acknowledge the new\nsettings.</p>\n<p>The new settings will not become effective until the <code>SETTINGS</code> acknowledgment\nis received and the <code>'localSettings'</code> event is emitted. It is possible to send\nmultiple <code>SETTINGS</code> frames while acknowledgment is still pending.</p>" }, { "textRaw": "http2session.unref()", "type": "method", "name": "unref", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "<p>Calls <a href=\"net.html#net_socket_unref\"><code>unref()</code></a> on this <code>Http2Session</code>\ninstance's underlying <a href=\"net.html#net_class_net_socket\"><code>net.Socket</code></a>.</p>" } ] }, { "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": "<p>Submits an <code>ALTSVC</code> frame (as defined by <a href=\"https://tools.ietf.org/html/rfc7838\">RFC 7838</a>) to the connected client.</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>Sending an <code>ALTSVC</code> frame with a specific stream ID indicates that the alternate\nservice is associated with the origin of the given <code>Http2Stream</code>.</p>\n<p>The <code>alt</code> and origin string <em>must</em> contain only ASCII bytes and are\nstrictly interpreted as a sequence of ASCII bytes. The special value <code>'clear'</code>\nmay be passed to clear any previously set alternative service for a given\ndomain.</p>\n<p>When a string is passed for the <code>originOrStream</code> argument, it will be parsed as\na URL and the origin will be derived. For instance, the origin for the\nHTTP URL <code>'https://example.org/foo/bar'</code> is the ASCII string\n<code>'https://example.org'</code>. An error will be thrown if either the given string\ncannot be parsed as a URL or if a valid origin cannot be derived.</p>\n<p>A <code>URL</code> object, or any object with an <code>origin</code> property, may be passed as\n<code>originOrStream</code>, in which case the value of the <code>origin</code> property will be\nused. The value of the <code>origin</code> property <em>must</em> be a properly serialized\nASCII origin.</p>" }, { "textRaw": "serverhttp2session.origin(...origins)", "type": "method", "name": "origin", "meta": { "added": [ "v10.12.0" ], "changes": [] }, "signatures": [ { "params": [ { "name": "...origins" } ] } ], "desc": "<p>Submits an <code>ORIGIN</code> frame (as defined by <a href=\"https://tools.ietf.org/html/rfc8336\">RFC 8336</a>) to the connected client\nto advertise the set of origins for which the server is capable of providing\nauthoritative responses.</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>When a string is passed as an <code>origin</code>, it will be parsed as a URL and the\norigin will be derived. For instance, the origin for the HTTP URL\n<code>'https://example.org/foo/bar'</code> is the ASCII string\n<code>'https://example.org'</code>. An error will be thrown if either the given string\ncannot be parsed as a URL or if a valid origin cannot be derived.</p>\n<p>A <code>URL</code> object, or any object with an <code>origin</code> property, may be passed as\nan <code>origin</code>, in which case the value of the <code>origin</code> property will be\nused. The value of the <code>origin</code> property <em>must</em> be a properly serialized\nASCII origin.</p>\n<p>Alternatively, the <code>origins</code> option may be used when creating a new HTTP/2\nserver using the <code>http2.createSecureServer()</code> method:</p>\n<pre><code class=\"language-js\">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</code></pre>" } ], "modules": [ { "textRaw": "Specifying alternative services", "name": "specifying_alternative_services", "desc": "<p>The format of the <code>alt</code> parameter is strictly defined by <a href=\"https://tools.ietf.org/html/rfc7838\">RFC 7838</a> as an\nASCII string containing a comma-delimited list of \"alternative\" protocols\nassociated with a specific host and port.</p>\n<p>For example, the value <code>'h2=\"example.org:81\"'</code> indicates that the HTTP/2\nprotocol is available on the host <code>'example.org'</code> on TCP/IP port 81. The\nhost and port <em>must</em> be contained within the quote (<code>\"</code>) characters.</p>\n<p>Multiple alternatives may be specified, for instance: <code>'h2=\"example.org:81\", h2=\":82\"'</code>.</p>\n<p>The protocol identifier (<code>'h2'</code> in the examples) may be any valid\n<a href=\"https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids\">ALPN Protocol ID</a>.</p>\n<p>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.</p>", "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": "<p>The <code>'altsvc'</code> event is emitted whenever an <code>ALTSVC</code> frame is received by\nthe client. The event is emitted with the <code>ALTSVC</code> value, origin, and stream\nID. If no <code>origin</code> is provided in the <code>ALTSVC</code> frame, <code>origin</code> will\nbe an empty string.</p>\n<pre><code class=\"language-js\">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</code></pre>" }, { "textRaw": "Event: 'origin'", "type": "event", "name": "origin", "meta": { "added": [ "v10.12.0" ], "changes": [] }, "params": [ { "textRaw": "`origins` {string[]}", "name": "origins", "type": "string[]" } ], "desc": "<p>The <code>'origin'</code> event is emitted whenever an <code>ORIGIN</code> frame is received by\nthe client. The event is emitted with an array of <code>origin</code> strings. The\n<code>http2session.originSet</code> will be updated to include the received\norigins.</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>The <code>'origin'</code> event is only emitted when using a secure TLS connection.</p>" } ], "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": "<p>For HTTP/2 Client <code>Http2Session</code> instances only, the <code>http2session.request()</code>\ncreates and returns an <code>Http2Stream</code> instance that can be used to send an\nHTTP/2 request to the connected server.</p>\n<p>This method is only available if <code>http2session.type</code> is equal to\n<code>http2.constants.NGHTTP2_SESSION_CLIENT</code>.</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event\nis emitted immediately after queuing the last chunk of payload data to be sent.\nThe <code>http2stream.sendTrailers()</code> method can then be called to send trailing\nheaders to the peer.</p>\n<p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically\nclose when the final <code>DATA</code> frame is transmitted. User code must call either\n<code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the\n<code>Http2Stream</code>.</p>\n<p>The <code>:method</code> and <code>:path</code> pseudo-headers are not specified within <code>headers</code>,\nthey respectively default to:</p>\n<ul>\n<li><code>:method</code> = <code>'GET'</code></li>\n<li><code>:path</code> = <code>/</code></li>\n</ul>" } ] }, { "textRaw": "Class: Http2Stream", "type": "class", "name": "Http2Stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<ul>\n<li>Extends: <a href=\"stream.html#stream_class_stream_duplex\" class=\"type\"><stream.Duplex></a></li>\n</ul>\n<p>Each instance of the <code>Http2Stream</code> class represents a bidirectional HTTP/2\ncommunications stream over an <code>Http2Session</code> instance. Any single <code>Http2Session</code>\nmay have up to 2<sup>31</sup>-1 <code>Http2Stream</code> instances over its lifetime.</p>\n<p>User code will not construct <code>Http2Stream</code> instances directly. Rather, these\nare created, managed, and provided to user code through the <code>Http2Session</code>\ninstance. On the server, <code>Http2Stream</code> instances are created either in response\nto an incoming HTTP request (and handed off to user code via the <code>'stream'</code>\nevent), or in response to a call to the <code>http2stream.pushStream()</code> method.\nOn the client, <code>Http2Stream</code> instances are created and returned when either the\n<code>http2session.request()</code> method is called, or in response to an incoming\n<code>'push'</code> event.</p>\n<p>The <code>Http2Stream</code> class is a base for the <a href=\"#http2_class_serverhttp2stream\"><code>ServerHttp2Stream</code></a> and\n<a href=\"#http2_class_clienthttp2stream\"><code>ClientHttp2Stream</code></a> classes, each of which is used specifically by either\nthe Server or Client side, respectively.</p>\n<p>All <code>Http2Stream</code> instances are <a href=\"stream.html#stream_class_stream_duplex\"><code>Duplex</code></a> streams. The <code>Writable</code> side of the\n<code>Duplex</code> is used to send data to the connected peer, while the <code>Readable</code> side\nis used to receive data sent by the connected peer.</p>", "modules": [ { "textRaw": "Http2Stream Lifecycle", "name": "http2stream_lifecycle", "modules": [ { "textRaw": "Creation", "name": "creation", "desc": "<p>On the server side, instances of <a href=\"#http2_class_serverhttp2stream\"><code>ServerHttp2Stream</code></a> are created either\nwhen:</p>\n<ul>\n<li>A new HTTP/2 <code>HEADERS</code> frame with a previously unused stream ID is received;</li>\n<li>The <code>http2stream.pushStream()</code> method is called.</li>\n</ul>\n<p>On the client side, instances of <a href=\"#http2_class_clienthttp2stream\"><code>ClientHttp2Stream</code></a> are created when the\n<code>http2session.request()</code> method is called.</p>\n<p>On the client, the <code>Http2Stream</code> instance returned by <code>http2session.request()</code>\nmay not be immediately ready for use if the parent <code>Http2Session</code> has not yet\nbeen fully established. In such cases, operations called on the <code>Http2Stream</code>\nwill be buffered until the <code>'ready'</code> event is emitted. User code should rarely,\nif ever, need to handle the <code>'ready'</code> event directly. The ready status of an\n<code>Http2Stream</code> can be determined by checking the value of <code>http2stream.id</code>. If\nthe value is <code>undefined</code>, the stream is not yet ready for use.</p>", "type": "module", "displayName": "Creation" }, { "textRaw": "Destruction", "name": "destruction", "desc": "<p>All <a href=\"#http2_class_http2stream\"><code>Http2Stream</code></a> instances are destroyed either when:</p>\n<ul>\n<li>An <code>RST_STREAM</code> frame for the stream is received by the connected peer,\nand (for client streams only) pending data has been read.</li>\n<li>The <code>http2stream.close()</code> method is called, and (for client streams only)\npending data has been read.</li>\n<li>The <code>http2stream.destroy()</code> or <code>http2session.destroy()</code> methods are called.</li>\n</ul>\n<p>When an <code>Http2Stream</code> instance is destroyed, an attempt will be made to send an\n<code>RST_STREAM</code> frame will be sent to the connected peer.</p>\n<p>When the <code>Http2Stream</code> instance is destroyed, the <code>'close'</code> event will\nbe emitted. Because <code>Http2Stream</code> is an instance of <code>stream.Duplex</code>, the\n<code>'end'</code> event will also be emitted if the stream data is currently flowing.\nThe <code>'error'</code> event may also be emitted if <code>http2stream.destroy()</code> was called\nwith an <code>Error</code> passed as the first argument.</p>\n<p>After the <code>Http2Stream</code> has been destroyed, the <code>http2stream.destroyed</code>\nproperty will be <code>true</code> and the <code>http2stream.rstCode</code> property will specify the\n<code>RST_STREAM</code> error code. The <code>Http2Stream</code> instance is no longer usable once\ndestroyed.</p>", "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": "<p>The <code>'aborted'</code> event is emitted whenever a <code>Http2Stream</code> instance is\nabnormally aborted in mid-communication.</p>\n<p>The <code>'aborted'</code> event will only be emitted if the <code>Http2Stream</code> writable side\nhas not been ended.</p>" }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'close'</code> event is emitted when the <code>Http2Stream</code> is destroyed. Once\nthis event is emitted, the <code>Http2Stream</code> instance is no longer usable.</p>\n<p>The HTTP/2 error code used when closing the stream can be retrieved using\nthe <code>http2stream.rstCode</code> property. If the code is any value other than\n<code>NGHTTP2_NO_ERROR</code> (<code>0</code>), an <code>'error'</code> event will have also been emitted.</p>" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`error` {Error}", "name": "error", "type": "Error" } ], "desc": "<p>The <code>'error'</code> event is emitted when an error occurs during the processing of\nan <code>Http2Stream</code>.</p>" }, { "textRaw": "Event: 'frameError'", "type": "event", "name": "frameError", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'frameError'</code> 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 <code>Http2Stream</code> instance will be destroyed immediately after the\n<code>'frameError'</code> event is emitted.</p>" }, { "textRaw": "Event: 'timeout'", "type": "event", "name": "timeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'timeout'</code> event is emitted after no activity is received for this\n<code>Http2Stream</code> within the number of milliseconds set using\n<code>http2stream.setTimeout()</code>.</p>" }, { "textRaw": "Event: 'trailers'", "type": "event", "name": "trailers", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'trailers'</code> event is emitted when a block of headers associated with\ntrailing header fields is received. The listener callback is passed the\n<a href=\"#http2_headers_object\">HTTP/2 Headers Object</a> and flags associated with the headers.</p>\n<p>Note that this event might not be emitted if <code>http2stream.end()</code> is called\nbefore trailers are received and the incoming data is not being read or\nlistened for.</p>\n<pre><code class=\"language-js\">stream.on('trailers', (headers, flags) => {\n console.log(headers);\n});\n</code></pre>" }, { "textRaw": "Event: 'wantTrailers'", "type": "event", "name": "wantTrailers", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'wantTrailers'</code> event is emitted when the <code>Http2Stream</code> has queued the\nfinal <code>DATA</code> frame to be sent on a frame and the <code>Http2Stream</code> is ready to send\ntrailing headers. When initiating a request or response, the <code>waitForTrailers</code>\noption must be set for this event to be emitted.</p>" } ], "properties": [ { "textRaw": "`aborted` {boolean}", "type": "boolean", "name": "aborted", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>Set to <code>true</code> if the <code>Http2Stream</code> instance was aborted abnormally. When set,\nthe <code>'aborted'</code> event will have been emitted.</p>" }, { "textRaw": "`bufferSize` {number}", "type": "number", "name": "bufferSize", "meta": { "added": [ "v10.16.0" ], "changes": [] }, "desc": "<p>This property shows the number of characters currently buffered to be written.\nSee <a href=\"net.html#net_socket_buffersize\"><code>net.Socket.bufferSize</code></a> for details.</p>" }, { "textRaw": "`closed` {boolean}", "type": "boolean", "name": "closed", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "<p>Set to <code>true</code> if the <code>Http2Stream</code> instance has been closed.</p>" }, { "textRaw": "`destroyed` {boolean}", "type": "boolean", "name": "destroyed", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>Set to <code>true</code> if the <code>Http2Stream</code> instance has been destroyed and is no longer\nusable.</p>" }, { "textRaw": "`endAfterHeaders` {boolean}", "type": "boolean", "name": "endAfterHeaders", "meta": { "added": [ "v10.11.0" ], "changes": [] }, "desc": "<p>Set the <code>true</code> if the <code>END_STREAM</code> 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 <code>Http2Stream</code> will be closed.</p>" }, { "textRaw": "`pending` {boolean}", "type": "boolean", "name": "pending", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "<p>Set to <code>true</code> if the <code>Http2Stream</code> instance has not yet been assigned a\nnumeric stream identifier.</p>" }, { "textRaw": "`rstCode` {number}", "type": "number", "name": "rstCode", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>Set to the <code>RST_STREAM</code> <a href=\"#error_codes\">error code</a> reported when the <code>Http2Stream</code> is\ndestroyed after either receiving an <code>RST_STREAM</code> frame from the connected peer,\ncalling <code>http2stream.close()</code>, or <code>http2stream.destroy()</code>. Will be\n<code>undefined</code> if the <code>Http2Stream</code> has not been closed.</p>" }, { "textRaw": "`sentHeaders` {HTTP/2 Headers Object}", "type": "HTTP/2 Headers Object", "name": "sentHeaders", "meta": { "added": [ "v9.5.0" ], "changes": [] }, "desc": "<p>An object containing the outbound headers sent for this <code>Http2Stream</code>.</p>" }, { "textRaw": "`sentInfoHeaders` {HTTP/2 Headers Object[]}", "type": "HTTP/2 Headers Object[]", "name": "sentInfoHeaders", "meta": { "added": [ "v9.5.0" ], "changes": [] }, "desc": "<p>An array of objects containing the outbound informational (additional) headers\nsent for this <code>Http2Stream</code>.</p>" }, { "textRaw": "`sentTrailers` {HTTP/2 Headers Object}", "type": "HTTP/2 Headers Object", "name": "sentTrailers", "meta": { "added": [ "v9.5.0" ], "changes": [] }, "desc": "<p>An object containing the outbound trailers sent for this <code>HttpStream</code>.</p>" }, { "textRaw": "`session` {Http2Session}", "type": "Http2Session", "name": "session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>A reference to the <code>Http2Session</code> instance that owns this <code>Http2Stream</code>. The\nvalue will be <code>undefined</code> after the <code>Http2Stream</code> instance is destroyed.</p>" }, { "textRaw": "http2stream.state", "name": "state", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>Provides miscellaneous information about the current state of the\n<code>Http2Stream</code>.</p>\n<ul>\n<li>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" class=\"type\"><Object></a></p>\n<ul>\n<li><code>localWindowSize</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The number of bytes the connected peer may send\nfor this <code>Http2Stream</code> without receiving a <code>WINDOW_UPDATE</code>.</li>\n<li><code>state</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> A flag indicating the low-level current state of the\n<code>Http2Stream</code> as determined by <code>nghttp2</code>.</li>\n<li><code>localClose</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> <code>true</code> if this <code>Http2Stream</code> has been closed locally.</li>\n<li><code>remoteClose</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> <code>true</code> if this <code>Http2Stream</code> has been closed\nremotely.</li>\n<li><code>sumDependencyWeight</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The sum weight of all <code>Http2Stream</code>\ninstances that depend on this <code>Http2Stream</code> as specified using\n<code>PRIORITY</code> frames.</li>\n<li><code>weight</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The priority weight of this <code>Http2Stream</code>.</li>\n</ul>\n</li>\n</ul>\n<p>A current state of this <code>Http2Stream</code>.</p>" } ], "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": "<p>Closes the <code>Http2Stream</code> instance by sending an <code>RST_STREAM</code> frame to the\nconnected HTTP/2 peer.</p>" }, { "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": "<p>Updates the priority for this <code>Http2Stream</code> instance.</p>" }, { "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": "<pre><code class=\"language-js\">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</code></pre>" }, { "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": "<p>Sends a trailing <code>HEADERS</code> frame to the connected HTTP/2 peer. This method\nwill cause the <code>Http2Stream</code> to be immediately closed and must only be\ncalled after the <code>'wantTrailers'</code> event has been emitted. When sending a\nrequest or sending a response, the <code>options.waitForTrailers</code> option must be set\nin order to keep the <code>Http2Stream</code> open after the final <code>DATA</code> frame so that\ntrailers can be sent.</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header\nfields (e.g. <code>':method'</code>, <code>':path'</code>, etc).</p>" } ] }, { "textRaw": "Class: ClientHttp2Stream", "type": "class", "name": "ClientHttp2Stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<ul>\n<li>Extends <a href=\"http2.html#http2_class_http2stream\" class=\"type\"><Http2Stream></a></li>\n</ul>\n<p>The <code>ClientHttp2Stream</code> class is an extension of <code>Http2Stream</code> that is\nused exclusively on HTTP/2 Clients. <code>Http2Stream</code> instances on the client\nprovide events such as <code>'response'</code> and <code>'push'</code> that are only relevant on\nthe client.</p>", "events": [ { "textRaw": "Event: 'continue'", "type": "event", "name": "continue", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "params": [], "desc": "<p>Emitted when the server sends a <code>100 Continue</code> status, usually because\nthe request contained <code>Expect: 100-continue</code>. This is an instruction that\nthe client should send the request body.</p>" }, { "textRaw": "Event: 'headers'", "type": "event", "name": "headers", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'headers'</code> event is emitted when an additional block of headers is received\nfor a stream, such as when a block of <code>1xx</code> informational headers is received.\nThe listener callback is passed the <a href=\"#http2_headers_object\">HTTP/2 Headers Object</a> and flags\nassociated with the headers.</p>\n<pre><code class=\"language-js\">stream.on('headers', (headers, flags) => {\n console.log(headers);\n});\n</code></pre>" }, { "textRaw": "Event: 'push'", "type": "event", "name": "push", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'push'</code> event is emitted when response headers for a Server Push stream\nare received. The listener callback is passed the <a href=\"#http2_headers_object\">HTTP/2 Headers Object</a> and\nflags associated with the headers.</p>\n<pre><code class=\"language-js\">stream.on('push', (headers, flags) => {\n console.log(headers);\n});\n</code></pre>" }, { "textRaw": "Event: 'response'", "type": "event", "name": "response", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'response'</code> event is emitted when a response <code>HEADERS</code> frame has been\nreceived for this stream from the connected HTTP/2 server. The listener is\ninvoked with two arguments: an <code>Object</code> containing the received\n<a href=\"#http2_headers_object\">HTTP/2 Headers Object</a>, and flags associated with the headers.</p>\n<pre><code class=\"language-js\">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</code></pre>" } ] }, { "textRaw": "Class: ServerHttp2Stream", "type": "class", "name": "ServerHttp2Stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<ul>\n<li>Extends: <a href=\"http2.html#http2_class_http2stream\" class=\"type\"><Http2Stream></a></li>\n</ul>\n<p>The <code>ServerHttp2Stream</code> class is an extension of <a href=\"#http2_class_http2stream\"><code>Http2Stream</code></a> that is\nused exclusively on HTTP/2 Servers. <code>Http2Stream</code> instances on the server\nprovide additional methods such as <code>http2stream.pushStream()</code> and\n<code>http2stream.respond()</code> that are only relevant on the server.</p>", "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": "<p>Sends an additional informational <code>HEADERS</code> frame to the connected HTTP/2 peer.</p>" }, { "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": "<p>Initiates a push stream. The callback is invoked with the new <code>Http2Stream</code>\ninstance created for the push stream passed as the second argument, or an\n<code>Error</code> passed as the first argument.</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>Setting the weight of a push stream is not allowed in the <code>HEADERS</code> frame. Pass\na <code>weight</code> value to <code>http2stream.priority</code> with the <code>silent</code> option set to\n<code>true</code> to enable server-side bandwidth balancing between concurrent streams.</p>\n<p>Calling <code>http2stream.pushStream()</code> from within a pushed stream is not permitted\nand will throw an error.</p>" }, { "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": "<pre><code class=\"language-js\">const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n stream.respond({ ':status': 200 });\n stream.end('some data');\n});\n</code></pre>\n<p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event\nwill be emitted immediately after queuing the last chunk of payload data to be\nsent. The <code>http2stream.sendTrailers()</code> method can then be used to sent trailing\nheader fields to the peer.</p>\n<p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically\nclose when the final <code>DATA</code> frame is transmitted. User code must call either\n<code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the\n<code>Http2Stream</code>.</p>\n<pre><code class=\"language-js\">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</code></pre>" }, { "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": "<p>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 <code>Http2Stream</code> will be\nclosed using an <code>RST_STREAM</code> frame using the standard <code>INTERNAL_ERROR</code> code.</p>\n<p>When used, the <code>Http2Stream</code> object's <code>Duplex</code> interface will be closed\nautomatically.</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>The optional <code>options.statCheck</code> function may be specified to give user code\nan opportunity to set additional content headers based on the <code>fs.Stat</code> details\nof the given fd. If the <code>statCheck</code> function is provided, the\n<code>http2stream.respondWithFD()</code> method will perform an <code>fs.fstat()</code> call to\ncollect details on the provided file descriptor.</p>\n<p>The <code>offset</code> and <code>length</code> options may be used to limit the response to a\nspecific range subset. This can be used, for instance, to support HTTP Range\nrequests.</p>\n<p>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.</p>\n<p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event\nwill be emitted immediately after queuing the last chunk of payload data to be\nsent. The <code>http2stream.sendTrailers()</code> method can then be used to sent trailing\nheader fields to the peer.</p>\n<p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically\nclose when the final <code>DATA</code> frame is transmitted. User code <em>must</em> call either\n<code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the\n<code>Http2Stream</code>.</p>\n<pre><code class=\"language-js\">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</code></pre>" }, { "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": "<p>Sends a regular file as the response. The <code>path</code> must specify a regular file\nor an <code>'error'</code> event will be emitted on the <code>Http2Stream</code> object.</p>\n<p>When used, the <code>Http2Stream</code> object's <code>Duplex</code> interface will be closed\nautomatically.</p>\n<p>The optional <code>options.statCheck</code> function may be specified to give user code\nan opportunity to set additional content headers based on the <code>fs.Stat</code> details\nof the given file:</p>\n<p>If an error occurs while attempting to read the file data, the <code>Http2Stream</code>\nwill be closed using an <code>RST_STREAM</code> frame using the standard <code>INTERNAL_ERROR</code>\ncode. If the <code>onError</code> callback is defined, then it will be called. Otherwise\nthe stream will be destroyed.</p>\n<p>Example using a file path:</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>The <code>options.statCheck</code> function may also be used to cancel the send operation\nby returning <code>false</code>. For instance, a conditional request may check the stat\nresults to determine if the file has been modified to return an appropriate\n<code>304</code> response:</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>The <code>content-length</code> header field will be automatically set.</p>\n<p>The <code>offset</code> and <code>length</code> options may be used to limit the response to a\nspecific range subset. This can be used, for instance, to support HTTP Range\nrequests.</p>\n<p>The <code>options.onError</code> 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.</p>\n<p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event\nwill be emitted immediately after queuing the last chunk of payload data to be\nsent. The <code>http2stream.sendTrailers()</code> method can then be used to sent trailing\nheader fields to the peer.</p>\n<p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically\nclose when the final <code>DATA</code> frame is transmitted. User code must call either\n<code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the\n<code>Http2Stream</code>.</p>\n<pre><code class=\"language-js\">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</code></pre>" } ], "properties": [ { "textRaw": "`headersSent` {boolean}", "type": "boolean", "name": "headersSent", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>True if headers were sent, false otherwise (read-only).</p>" }, { "textRaw": "`pushAllowed` {boolean}", "type": "boolean", "name": "pushAllowed", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>Read-only property mapped to the <code>SETTINGS_ENABLE_PUSH</code> flag of the remote\nclient's most recent <code>SETTINGS</code> frame. Will be <code>true</code> if the remote peer\naccepts push streams, <code>false</code> otherwise. Settings are the same for every\n<code>Http2Stream</code> in the same <code>Http2Session</code>.</p>" } ] }, { "textRaw": "Class: Http2Server", "type": "class", "name": "Http2Server", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<ul>\n<li>Extends: <a href=\"net.html#net_class_net_server\" class=\"type\"><net.Server></a></li>\n</ul>\n<p>Instances of <code>Http2Server</code> are created using the <code>http2.createServer()</code>\nfunction. The <code>Http2Server</code> class is not exported directly by the <code>http2</code>\nmodule.</p>", "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": "<p>If a <a href=\"#http2_event_request\"><code>'request'</code></a> listener is registered or <a href=\"#http2_http2_createserver_options_onrequesthandler\"><code>http2.createServer()</code></a> is\nsupplied a callback function, the <code>'checkContinue'</code> event is emitted each time\na request with an HTTP <code>Expect: 100-continue</code> is received. If this event is\nnot listened for, the server will automatically respond with a status\n<code>100 Continue</code> as appropriate.</p>\n<p>Handling this event involves calling <a href=\"#http2_response_writecontinue\"><code>response.writeContinue()</code></a> 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.</p>\n<p>Note that when this event is emitted and handled, the <a href=\"#http2_event_request\"><code>'request'</code></a> event will\nnot be emitted.</p>" }, { "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": "<p>Emitted each time there is a request. Note that there may be multiple requests\nper session. See the <a href=\"#http2_compatibility_api\">Compatibility API</a>.</p>" }, { "textRaw": "Event: 'session'", "type": "event", "name": "session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'session'</code> event is emitted when a new <code>Http2Session</code> is created by the\n<code>Http2Server</code>.</p>" }, { "textRaw": "Event: 'sessionError'", "type": "event", "name": "sessionError", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'sessionError'</code> event is emitted when an <code>'error'</code> event is emitted by\nan <code>Http2Session</code> object associated with the <code>Http2Server</code>.</p>" }, { "textRaw": "Event: 'stream'", "type": "event", "name": "stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'stream'</code> event is emitted when a <code>'stream'</code> event has been emitted by\nan <code>Http2Session</code> associated with the server.</p>\n<pre><code class=\"language-js\">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</code></pre>" }, { "textRaw": "Event: 'timeout'", "type": "event", "name": "timeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'timeout'</code> event is emitted when there is no activity on the Server for\na given number of milliseconds set using <code>http2server.setTimeout()</code>.\n<strong>Default:</strong> 2 minutes.</p>" } ], "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": "<p>Stops the server from accepting new connections. See <a href=\"net.html#net_server_close_callback\"><code>net.Server.close()</code></a>.</p>\n<p>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 <a href=\"#http2_http2session_close_callback\"><code>http2session.close()</code></a> on active sessions.</p>" }, { "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": "<p>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 <code>Http2Server</code> after <code>msecs</code> milliseconds.</p>\n<p>The given callback is registered as a listener on the <code>'timeout'</code> event.</p>\n<p>In case of no callback function were assigned, a new <code>ERR_INVALID_CALLBACK</code>\nerror will be thrown.</p>" } ] }, { "textRaw": "Class: Http2SecureServer", "type": "class", "name": "Http2SecureServer", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<ul>\n<li>Extends: <a href=\"tls.html#tls_class_tls_server\" class=\"type\"><tls.Server></a></li>\n</ul>\n<p>Instances of <code>Http2SecureServer</code> are created using the\n<code>http2.createSecureServer()</code> function. The <code>Http2SecureServer</code> class is not\nexported directly by the <code>http2</code> module.</p>", "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": "<p>If a <a href=\"#http2_event_request\"><code>'request'</code></a> listener is registered or <a href=\"#http2_http2_createsecureserver_options_onrequesthandler\"><code>http2.createSecureServer()</code></a>\nis supplied a callback function, the <code>'checkContinue'</code> event is emitted each\ntime a request with an HTTP <code>Expect: 100-continue</code> is received. If this event\nis not listened for, the server will automatically respond with a status\n<code>100 Continue</code> as appropriate.</p>\n<p>Handling this event involves calling <a href=\"#http2_response_writecontinue\"><code>response.writeContinue()</code></a> 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.</p>\n<p>Note that when this event is emitted and handled, the <a href=\"#http2_event_request\"><code>'request'</code></a> event will\nnot be emitted.</p>" }, { "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": "<p>Emitted each time there is a request. Note that there may be multiple requests\nper session. See the <a href=\"#http2_compatibility_api\">Compatibility API</a>.</p>" }, { "textRaw": "Event: 'session'", "type": "event", "name": "session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'session'</code> event is emitted when a new <code>Http2Session</code> is created by the\n<code>Http2SecureServer</code>.</p>" }, { "textRaw": "Event: 'sessionError'", "type": "event", "name": "sessionError", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'sessionError'</code> event is emitted when an <code>'error'</code> event is emitted by\nan <code>Http2Session</code> object associated with the <code>Http2SecureServer</code>.</p>" }, { "textRaw": "Event: 'stream'", "type": "event", "name": "stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'stream'</code> event is emitted when a <code>'stream'</code> event has been emitted by\nan <code>Http2Session</code> associated with the server.</p>\n<pre><code class=\"language-js\">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</code></pre>" }, { "textRaw": "Event: 'timeout'", "type": "event", "name": "timeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'timeout'</code> event is emitted when there is no activity on the Server for\na given number of milliseconds set using <code>http2secureServer.setTimeout()</code>.\n<strong>Default:</strong> 2 minutes.</p>" }, { "textRaw": "Event: 'unknownProtocol'", "type": "event", "name": "unknownProtocol", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'unknownProtocol'</code> 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. A timeout may be specified using the\n<code>'unknownProtocolTimeout'</code> option passed to <a href=\"#http2_http2_createsecureserver_options_onrequesthandler\"><code>http2.createSecureServer()</code></a>.\nSee the <a href=\"#http2_compatibility_api\">Compatibility API</a>.</p>" } ], "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": "<p>Stops the server from accepting new connections. See <a href=\"tls.html#tls_server_close_callback\"><code>tls.Server.close()</code></a>.</p>\n<p>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 <a href=\"#http2_http2session_close_callback\"><code>http2session.close()</code></a> on active sessions.</p>" }, { "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": "<p>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 <code>Http2SecureServer</code> after <code>msecs</code> milliseconds.</p>\n<p>The given callback is registered as a listener on the <code>'timeout'</code> event.</p>\n<p>In case of no callback function were assigned, a new <code>ERR_INVALID_CALLBACK</code>\nerror will be thrown.</p>" } ] } ], "methods": [ { "textRaw": "http2.createServer(options[, onRequestHandler])", "type": "method", "name": "createServer", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v10.24.0", "pr-url": "https://github.com/nodejs-private/node-private/pull/248", "description": "Added `unknownProtocolTimeout` option with a default of 10000." }, { "version": "v10.21.0", "pr-url": "https://github.com/nodejs-private/node-private/pull/204", "description": "Added `maxSettings` option with a default of 32." }, { "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": "`maxSettings` {number} Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`.", "name": "maxSettings", "type": "number", "default": "`32`", "desc": "Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`." }, { "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": "`unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that a server should wait when an [`'unknownProtocol'`][] is emitted. If the socket has not been destroyed by that time the server will destroy it. **Default:** `10000`.", "name": "unknownProtocolTimeout", "type": "number", "default": "`10000`", "desc": "Specifies a timeout in milliseconds that a server should wait when an [`'unknownProtocol'`][] is emitted. If the socket has not been destroyed by that time the server will destroy it." } ] }, { "textRaw": "`onRequestHandler` {Function} See [Compatibility API][]", "name": "onRequestHandler", "type": "Function", "desc": "See [Compatibility API][]", "optional": true } ] } ], "desc": "<p>Returns a <code>net.Server</code> instance that creates and manages <code>Http2Session</code>\ninstances.</p>\n<p>Since there are no browsers known that support\n<a href=\"https://http2.github.io/faq/#does-http2-require-encryption\">unencrypted HTTP/2</a>, the use of\n<a href=\"#http2_http2_createsecureserver_options_onrequesthandler\"><code>http2.createSecureServer()</code></a> is necessary when communicating\nwith browser clients.</p>\n<pre><code class=\"language-js\">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</code></pre>" }, { "textRaw": "http2.createSecureServer(options[, onRequestHandler])", "type": "method", "name": "createSecureServer", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v10.24.0", "pr-url": "https://github.com/nodejs-private/node-private/pull/248", "description": "Added `unknownProtocolTimeout` option with a default of 10000." }, { "version": "v10.21.0", "pr-url": "https://github.com/nodejs-private/node-private/pull/204", "description": "Added `maxSettings` option with a default of 32." }, { "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": "`maxSettings` {number} Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`.", "name": "maxSettings", "type": "number", "default": "`32`", "desc": "Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`." }, { "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": "`unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that a server should wait when an [`'unknownProtocol'`][] event is emitted. If the socket has not been destroyed by that time the server will destroy it. **Default:** `10000`.", "name": "unknownProtocolTimeout", "type": "number", "default": "`10000`", "desc": "Specifies a timeout in milliseconds that a server should wait when an [`'unknownProtocol'`][] event is emitted. If the socket has not been destroyed by that time the server will destroy it." } ] }, { "textRaw": "`onRequestHandler` {Function} See [Compatibility API][]", "name": "onRequestHandler", "type": "Function", "desc": "See [Compatibility API][]", "optional": true } ] } ], "desc": "<p>Returns a <code>tls.Server</code> instance that creates and manages <code>Http2Session</code>\ninstances.</p>\n<pre><code class=\"language-js\">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</code></pre>" }, { "textRaw": "http2.connect(authority[, options][, listener])", "type": "method", "name": "connect", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v10.24.0", "pr-url": "https://github.com/nodejs-private/node-private/pull/248", "description": "Added `unknownProtocolTimeout` option with a default of 10000." }, { "version": "v10.21.0", "pr-url": "https://github.com/nodejs-private/node-private/pull/204", "description": "Added `maxSettings` option with a default of 32." }, { "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": "`maxSettings` {number} Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`.", "name": "maxSettings", "type": "number", "default": "`32`", "desc": "Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`." }, { "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." }, { "textRaw": "`unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that a server should wait when an [`'unknownProtocol'`][] event is emitted. If the socket has not been destroyed by that time the server will destroy it. **Default:** `10000`.", "name": "unknownProtocolTimeout", "type": "number", "default": "`10000`", "desc": "Specifies a timeout in milliseconds that a server should wait when an [`'unknownProtocol'`][] event is emitted. If the socket has not been destroyed by that time the server will destroy it." } ], "optional": true }, { "textRaw": "`listener` {Function}", "name": "listener", "type": "Function", "optional": true } ] } ], "desc": "<p>Returns a <code>ClientHttp2Session</code> instance.</p>\n<pre><code class=\"language-js\">const http2 = require('http2');\nconst client = http2.connect('https://localhost:1234');\n\n/* Use the client */\n\nclient.close();\n</code></pre>" }, { "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": "<p>Returns an object containing the default settings for an <code>Http2Session</code>\ninstance. This method returns a new object instance every time it is called\nso instances returned may be safely modified for use.</p>" }, { "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": "<p>Returns a <code>Buffer</code> instance containing serialized representation of the given\nHTTP/2 settings as specified in the <a href=\"https://tools.ietf.org/html/rfc7540\">HTTP/2</a> specification. This is intended\nfor use with the <code>HTTP2-Settings</code> header field.</p>\n<pre><code class=\"language-js\">const http2 = require('http2');\n\nconst packed = http2.getPackedSettings({ enablePush: false });\n\nconsole.log(packed.toString('base64'));\n// Prints: AAIAAAAA\n</code></pre>" }, { "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": "<p>Returns a <a href=\"#http2_settings_object\">HTTP/2 Settings Object</a> containing the deserialized settings from\nthe given <code>Buffer</code> as generated by <code>http2.getPackedSettings()</code>.</p>" } ], "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": "<p><a id=\"error_codes\"></a></p>\n<table>\n<thead>\n<tr>\n<th>Value</th>\n<th>Name</th>\n<th>Constant</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>0x00</code></td>\n<td>No Error</td>\n<td><code>http2.constants.NGHTTP2_NO_ERROR</code></td>\n</tr>\n<tr>\n<td><code>0x01</code></td>\n<td>Protocol Error</td>\n<td><code>http2.constants.NGHTTP2_PROTOCOL_ERROR</code></td>\n</tr>\n<tr>\n<td><code>0x02</code></td>\n<td>Internal Error</td>\n<td><code>http2.constants.NGHTTP2_INTERNAL_ERROR</code></td>\n</tr>\n<tr>\n<td><code>0x03</code></td>\n<td>Flow Control Error</td>\n<td><code>http2.constants.NGHTTP2_FLOW_CONTROL_ERROR</code></td>\n</tr>\n<tr>\n<td><code>0x04</code></td>\n<td>Settings Timeout</td>\n<td><code>http2.constants.NGHTTP2_SETTINGS_TIMEOUT</code></td>\n</tr>\n<tr>\n<td><code>0x05</code></td>\n<td>Stream Closed</td>\n<td><code>http2.constants.NGHTTP2_STREAM_CLOSED</code></td>\n</tr>\n<tr>\n<td><code>0x06</code></td>\n<td>Frame Size Error</td>\n<td><code>http2.constants.NGHTTP2_FRAME_SIZE_ERROR</code></td>\n</tr>\n<tr>\n<td><code>0x07</code></td>\n<td>Refused Stream</td>\n<td><code>http2.constants.NGHTTP2_REFUSED_STREAM</code></td>\n</tr>\n<tr>\n<td><code>0x08</code></td>\n<td>Cancel</td>\n<td><code>http2.constants.NGHTTP2_CANCEL</code></td>\n</tr>\n<tr>\n<td><code>0x09</code></td>\n<td>Compression Error</td>\n<td><code>http2.constants.NGHTTP2_COMPRESSION_ERROR</code></td>\n</tr>\n<tr>\n<td><code>0x0a</code></td>\n<td>Connect Error</td>\n<td><code>http2.constants.NGHTTP2_CONNECT_ERROR</code></td>\n</tr>\n<tr>\n<td><code>0x0b</code></td>\n<td>Enhance Your Calm</td>\n<td><code>http2.constants.NGHTTP2_ENHANCE_YOUR_CALM</code></td>\n</tr>\n<tr>\n<td><code>0x0c</code></td>\n<td>Inadequate Security</td>\n<td><code>http2.constants.NGHTTP2_INADEQUATE_SECURITY</code></td>\n</tr>\n<tr>\n<td><code>0x0d</code></td>\n<td>HTTP/1.1 Required</td>\n<td><code>http2.constants.NGHTTP2_HTTP_1_1_REQUIRED</code></td>\n</tr>\n</tbody>\n</table>\n<p>The <code>'timeout'</code> event is emitted when there is no activity on the Server for\na given number of milliseconds set using <code>http2server.setTimeout()</code>.</p>", "type": "module", "displayName": "Error Codes for RST_STREAM and GOAWAY" } ] } ], "type": "module", "displayName": "Core API" }, { "textRaw": "Compatibility API", "name": "compatibility_api", "desc": "<p>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 <a href=\"http.html\">HTTP/1</a> and HTTP/2. This API targets only the\n<strong>public API</strong> of the <a href=\"http.html\">HTTP/1</a>. However many modules use internal\nmethods or state, and those <em>are not supported</em> as it is a completely\ndifferent implementation.</p>\n<p>The following example creates an HTTP/2 server using the compatibility\nAPI:</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>In order to create a mixed <a href=\"https.html\">HTTPS</a> and HTTP/2 server, refer to the\n<a href=\"#http2_alpn_negotiation\">ALPN negotiation</a> section.\nUpgrading from non-tls HTTP/1 servers is not supported.</p>\n<p>The HTTP/2 compatibility API is composed of <a href=\"\"><code>Http2ServerRequest</code></a> and\n<a href=\"\"><code>Http2ServerResponse</code></a>. 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.</p>", "modules": [ { "textRaw": "ALPN negotiation", "name": "alpn_negotiation", "desc": "<p>ALPN negotiation allows supporting both <a href=\"https.html\">HTTPS</a> and HTTP/2 over\nthe same socket. The <code>req</code> and <code>res</code> objects can be either HTTP/1 or\nHTTP/2, and an application <strong>must</strong> restrict itself to the public API of\n<a href=\"http.html\">HTTP/1</a>, and detect if it is possible to use the more advanced\nfeatures of HTTP/2.</p>\n<p>The following example creates a server that supports both protocols:</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>The <code>'request'</code> event works identically on both <a href=\"https.html\">HTTPS</a> and\nHTTP/2.</p>", "type": "module", "displayName": "ALPN negotiation" } ], "classes": [ { "textRaw": "Class: http2.Http2ServerRequest", "type": "class", "name": "http2.Http2ServerRequest", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>A <code>Http2ServerRequest</code> object is created by <a href=\"#http2_class_http2server\"><code>http2.Server</code></a> or\n<a href=\"#http2_class_http2secureserver\"><code>http2.SecureServer</code></a> and passed as the first argument to the\n<a href=\"#http2_event_request\"><code>'request'</code></a> event. It may be used to access a request status, headers, and\ndata.</p>\n<p>It implements the <a href=\"stream.html#stream_class_stream_readable\">Readable Stream</a> interface, as well as the\nfollowing additional events, methods, and properties.</p>", "events": [ { "textRaw": "Event: 'aborted'", "type": "event", "name": "aborted", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>The <code>'aborted'</code> event is emitted whenever a <code>Http2ServerRequest</code> instance is\nabnormally aborted in mid-communication.</p>\n<p>The <code>'aborted'</code> event will only be emitted if the <code>Http2ServerRequest</code> writable\nside has not been ended.</p>" }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>Indicates that the underlying <a href=\"#http2_class_http2stream\"><code>Http2Stream</code></a> was closed.\nJust like <code>'end'</code>, this event occurs only once per response.</p>" } ], "properties": [ { "textRaw": "`aborted` {boolean}", "type": "boolean", "name": "aborted", "meta": { "added": [ "v10.1.0" ], "changes": [] }, "desc": "<p>The <code>request.aborted</code> property will be <code>true</code> if the request has\nbeen aborted.</p>" }, { "textRaw": "`authority` {string}", "type": "string", "name": "authority", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>The request authority pseudo header field. It can also be accessed via\n<code>req.headers[':authority']</code>.</p>" }, { "textRaw": "`headers` {Object}", "type": "Object", "name": "headers", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>The request/response headers object.</p>\n<p>Key-value pairs of header names and values. Header names are lower-cased.</p>\n<pre><code class=\"language-js\">// 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</code></pre>\n<p>See <a href=\"#http2_headers_object\">HTTP/2 Headers Object</a>.</p>\n<p>In HTTP/2, the request path, hostname, protocol, and method are represented as\nspecial headers prefixed with the <code>:</code> character (e.g. <code>':path'</code>). These special\nheaders will be included in the <code>request.headers</code> 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:</p>\n<pre><code class=\"language-js\">removeAllHeaders(request.headers);\nassert(request.url); // Fails because the :path header has been removed\n</code></pre>" }, { "textRaw": "`httpVersion` {string}", "type": "string", "name": "httpVersion", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>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<code>'2.0'</code>.</p>\n<p>Also <code>message.httpVersionMajor</code> is the first integer and\n<code>message.httpVersionMinor</code> is the second.</p>" }, { "textRaw": "`method` {string}", "type": "string", "name": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>The request method as a string. Read-only. Examples: <code>'GET'</code>, <code>'DELETE'</code>.</p>" }, { "textRaw": "`rawHeaders` {string[]}", "type": "string[]", "name": "rawHeaders", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>The raw request/response headers list exactly as they were received.</p>\n<p>Note that the keys and values are in the same list. It is <em>not</em> a\nlist of tuples. So, the even-numbered offsets are key values, and the\nodd-numbered offsets are the associated values.</p>\n<p>Header names are not lowercased, and duplicates are not merged.</p>\n<pre><code class=\"language-js\">// 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</code></pre>" }, { "textRaw": "`rawTrailers` {string[]}", "type": "string[]", "name": "rawTrailers", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>The raw request/response trailer keys and values exactly as they were\nreceived. Only populated at the <code>'end'</code> event.</p>" }, { "textRaw": "`scheme` {string}", "type": "string", "name": "scheme", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>The request scheme pseudo header field indicating the scheme\nportion of the target URL.</p>" }, { "textRaw": "`socket` {net.Socket|tls.TLSSocket}", "type": "net.Socket|tls.TLSSocket", "name": "socket", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>Returns a <code>Proxy</code> object that acts as a <code>net.Socket</code> (or <code>tls.TLSSocket</code>) but\napplies getters, setters, and methods based on HTTP/2 logic.</p>\n<p><code>destroyed</code>, <code>readable</code>, and <code>writable</code> properties will be retrieved from and\nset on <code>request.stream</code>.</p>\n<p><code>destroy</code>, <code>emit</code>, <code>end</code>, <code>on</code> and <code>once</code> methods will be called on\n<code>request.stream</code>.</p>\n<p><code>setTimeout</code> method will be called on <code>request.stream.session</code>.</p>\n<p><code>pause</code>, <code>read</code>, <code>resume</code>, and <code>write</code> will throw an error with code\n<code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code>. See <a href=\"#http2_http2session_and_sockets\"><code>Http2Session</code> and Sockets</a> for\nmore information.</p>\n<p>All other interactions will be routed directly to the socket. With TLS support,\nuse <a href=\"tls.html#tls_tlssocket_getpeercertificate_detailed\"><code>request.socket.getPeerCertificate()</code></a> to obtain the client's\nauthentication details.</p>" }, { "textRaw": "`stream` {Http2Stream}", "type": "Http2Stream", "name": "stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>The <a href=\"#http2_class_http2stream\"><code>Http2Stream</code></a> object backing the request.</p>" }, { "textRaw": "`trailers` {Object}", "type": "Object", "name": "trailers", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>The request/response trailers object. Only populated at the <code>'end'</code> event.</p>" }, { "textRaw": "`url` {string}", "type": "string", "name": "url", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>Request URL string. This contains only the URL that is\npresent in the actual HTTP request. If the request is:</p>\n<pre><code class=\"language-txt\">GET /status?name=ryan HTTP/1.1\\r\\n\nAccept: text/plain\\r\\n\n\\r\\n\n</code></pre>\n<p>Then <code>request.url</code> will be:</p>\n<!-- eslint-disable semi -->\n<pre><code class=\"language-js\">'/status?name=ryan'\n</code></pre>\n<p>To parse the url into its parts <code>require('url').parse(request.url)</code>\ncan be used:</p>\n<pre><code class=\"language-txt\">$ 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</code></pre>\n<p>To extract the parameters from the query string, the\n<code>require('querystring').parse</code> function can be used, or\n<code>true</code> can be passed as the second argument to <code>require('url').parse</code>.</p>\n<pre><code class=\"language-txt\">$ 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</code></pre>" } ], "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": "<p>Calls <code>destroy()</code> on the <a href=\"#http2_class_http2stream\"><code>Http2Stream</code></a> that received\nthe <a href=\"#http2_class_http2_http2serverrequest\"><code>Http2ServerRequest</code></a>. If <code>error</code> is provided, an <code>'error'</code> event\nis emitted and <code>error</code> is passed as an argument to any listeners on the event.</p>\n<p>It does nothing if the stream was already destroyed.</p>" }, { "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": "<p>Sets the <a href=\"\"><code>Http2Stream</code></a>'s timeout value to <code>msecs</code>. If a callback is\nprovided, then it is added as a listener on the <code>'timeout'</code> event on\nthe response object.</p>\n<p>If no <code>'timeout'</code> listener is added to the request, the response, or\nthe server, then <a href=\"\"><code>Http2Stream</code></a>s are destroyed when they time out. If a\nhandler is assigned to the request, the response, or the server's <code>'timeout'</code>\nevents, timed out sockets must be handled explicitly.</p>" } ] }, { "textRaw": "Class: http2.Http2ServerResponse", "type": "class", "name": "http2.Http2ServerResponse", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>This object is created internally by an HTTP server, not by the user. It is\npassed as the second parameter to the <a href=\"#http2_event_request\"><code>'request'</code></a> event.</p>\n<p>The response inherits from <a href=\"stream.html#stream_stream\">Stream</a>, and additionally implements the\nfollowing:</p>", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>Indicates that the underlying <a href=\"\"><code>Http2Stream</code></a> was terminated before\n<a href=\"#http2_response_end_data_encoding_callback\"><code>response.end()</code></a> was called or able to flush.</p>" }, { "textRaw": "Event: 'finish'", "type": "event", "name": "finish", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "<p>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.</p>\n<p>After this event, no more events will be emitted on the response object.</p>" } ], "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": "<p>This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.</p>\n<p>Attempting to set a header field name or value that contains invalid characters\nwill result in a <a href=\"errors.html#errors_class_typeerror\"><code>TypeError</code></a> being thrown.</p>" }, { "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": "<p>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, <code>response.end()</code>, MUST be called on each response.</p>\n<p>If <code>data</code> is specified, it is equivalent to calling\n<a href=\"http.html#http_response_write_chunk_encoding_callback\"><code>response.write(data, encoding)</code></a> followed by <code>response.end(callback)</code>.</p>\n<p>If <code>callback</code> is specified, it will be called when the response stream\nis finished.</p>" }, { "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": "<p>Reads out a header that has already been queued but not sent to the client.\nNote that the name is case insensitive.</p>\n<pre><code class=\"language-js\">const contentType = response.getHeader('content-type');\n</code></pre>" }, { "textRaw": "response.getHeaderNames()", "type": "method", "name": "getHeaderNames", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string[]}", "name": "return", "type": "string[]" }, "params": [] } ], "desc": "<p>Returns an array containing the unique names of the current outgoing headers.\nAll header names are lowercase.</p>\n<pre><code class=\"language-js\">response.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headerNames = response.getHeaderNames();\n// headerNames === ['foo', 'set-cookie']\n</code></pre>" }, { "textRaw": "response.getHeaders()", "type": "method", "name": "getHeaders", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "desc": "<p>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.</p>\n<p>The object returned by the <code>response.getHeaders()</code> method <em>does not</em>\nprototypically inherit from the JavaScript <code>Object</code>. This means that typical\n<code>Object</code> methods such as <code>obj.toString()</code>, <code>obj.hasOwnProperty()</code>, and others\nare not defined and <em>will not work</em>.</p>\n<pre><code class=\"language-js\">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</code></pre>" }, { "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": "<p>Returns <code>true</code> if the header identified by <code>name</code> is currently set in the\noutgoing headers. Note that the header name matching is case-insensitive.</p>\n<pre><code class=\"language-js\">const hasContentType = response.hasHeader('content-type');\n</code></pre>" }, { "textRaw": "response.removeHeader(name)", "type": "method", "name": "removeHeader", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "<p>Removes a header that has been queued for implicit sending.</p>\n<pre><code class=\"language-js\">response.removeHeader('Content-Encoding');\n</code></pre>" }, { "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": "<p>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.</p>\n<pre><code class=\"language-js\">response.setHeader('Content-Type', 'text/html');\n</code></pre>\n<p>or</p>\n<pre><code class=\"language-js\">response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\n</code></pre>\n<p>Attempting to set a header field name or value that contains invalid characters\nwill result in a <a href=\"errors.html#errors_class_typeerror\"><code>TypeError</code></a> being thrown.</p>\n<p>When headers have been set with <a href=\"#http2_response_setheader_name_value\"><code>response.setHeader()</code></a>, they will be merged\nwith any headers passed to <a href=\"#http2_response_writehead_statuscode_statusmessage_headers\"><code>response.writeHead()</code></a>, with the headers passed\nto <a href=\"#http2_response_writehead_statuscode_statusmessage_headers\"><code>response.writeHead()</code></a> given precedence.</p>\n<pre><code class=\"language-js\">// 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</code></pre>" }, { "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": "<p>Sets the <a href=\"\"><code>Http2Stream</code></a>'s timeout value to <code>msecs</code>. If a callback is\nprovided, then it is added as a listener on the <code>'timeout'</code> event on\nthe response object.</p>\n<p>If no <code>'timeout'</code> listener is added to the request, the response, or\nthe server, then <a href=\"\"><code>Http2Stream</code></a>s are destroyed when they time out. If a\nhandler is assigned to the request, the response, or the server's <code>'timeout'</code>\nevents, timed out sockets must be handled explicitly.</p>" }, { "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": "<p>If this method is called and <a href=\"#http2_response_writehead_statuscode_statusmessage_headers\"><code>response.writeHead()</code></a> has not been called,\nit will switch to implicit header mode and flush the implicit headers.</p>\n<p>This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.</p>\n<p>Note that in the <code>http</code> module, the response body is omitted when the\nrequest is a HEAD request. Similarly, the <code>204</code> and <code>304</code> responses\n<em>must not</em> include a message body.</p>\n<p><code>chunk</code> can be a string or a buffer. If <code>chunk</code> is a string,\nthe second parameter specifies how to encode it into a byte stream.\nBy default the <code>encoding</code> is <code>'utf8'</code>. <code>callback</code> will be called when this chunk\nof data is flushed.</p>\n<p>This is the raw HTTP body and has nothing to do with higher-level multi-part\nbody encodings that may be used.</p>\n<p>The first time <a href=\"#http2_response_write_chunk_encoding_callback\"><code>response.write()</code></a> is called, it will send the buffered\nheader information and the first chunk of the body to the client. The second\ntime <a href=\"#http2_response_write_chunk_encoding_callback\"><code>response.write()</code></a> 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.</p>\n<p>Returns <code>true</code> if the entire data was flushed successfully to the kernel\nbuffer. Returns <code>false</code> if all or part of the data was queued in user memory.\n<code>'drain'</code> will be emitted when the buffer is free again.</p>" }, { "textRaw": "response.writeContinue()", "type": "method", "name": "writeContinue", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "<p>Sends a status <code>100 Continue</code> to the client, indicating that the request body\nshould be sent. See the <a href=\"#http2_event_checkcontinue\"><code>'checkContinue'</code></a> event on <code>Http2Server</code> and\n<code>Http2SecureServer</code>.</p>" }, { "textRaw": "response.writeHead(statusCode[, statusMessage][, headers])", "type": "method", "name": "writeHead", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v10.17.0", "pr-url": "https://github.com/nodejs/node/pull/25974", "description": "Return `this` from `writeHead()` to allow chaining with `end()`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {http2.Http2ServerResponse}", "name": "return", "type": "http2.Http2ServerResponse" }, "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": "<p>Sends a response header to the request. The status code is a 3-digit HTTP\nstatus code, like <code>404</code>. The last argument, <code>headers</code>, are the response headers.</p>\n<p>Returns a reference to the <code>Http2ServerResponse</code>, so that calls can be chained.</p>\n<p>For compatibility with <a href=\"http.html\">HTTP/1</a>, a human-readable <code>statusMessage</code> may be\npassed as the second argument. However, because the <code>statusMessage</code> has no\nmeaning within HTTP/2, the argument will have no effect and a process warning\nwill be emitted.</p>\n<pre><code class=\"language-js\">const body = 'hello world';\nresponse.writeHead(200, {\n 'Content-Length': Buffer.byteLength(body),\n 'Content-Type': 'text/plain' });\n</code></pre>\n<p>Note that Content-Length is given in bytes not characters. The\n<code>Buffer.byteLength()</code> 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.</p>\n<p>This method may be called at most one time on a message before\n<a href=\"#http2_response_end_data_encoding_callback\"><code>response.end()</code></a> is called.</p>\n<p>If <a href=\"#http2_response_write_chunk_encoding_callback\"><code>response.write()</code></a> or <a href=\"#http2_response_end_data_encoding_callback\"><code>response.end()</code></a> are called before calling\nthis, the implicit/mutable headers will be calculated and call this function.</p>\n<p>When headers have been set with <a href=\"#http2_response_setheader_name_value\"><code>response.setHeader()</code></a>, they will be merged\nwith any headers passed to <a href=\"#http2_response_writehead_statuscode_statusmessage_headers\"><code>response.writeHead()</code></a>, with the headers passed\nto <a href=\"#http2_response_writehead_statuscode_statusmessage_headers\"><code>response.writeHead()</code></a> given precedence.</p>\n<pre><code class=\"language-js\">// 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</code></pre>\n<p>Attempting to set a header field name or value that contains invalid characters\nwill result in a <a href=\"errors.html#errors_class_typeerror\"><code>TypeError</code></a> being thrown.</p>" }, { "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": "<p>Call <a href=\"#http2_http2stream_pushstream_headers_options_callback\"><code>http2stream.pushStream()</code></a> with the given headers, and wrap the\ngiven <a href=\"#http2_class_http2stream\"><code>Http2Stream</code></a> on a newly created <code>Http2ServerResponse</code> as the callback\nparameter if successful. When <code>Http2ServerRequest</code> is closed, the callback is\ncalled with an error <code>ERR_HTTP2_INVALID_STREAM</code>.</p>" } ], "properties": [ { "textRaw": "`connection` {net.Socket|tls.TLSSocket}", "type": "net.Socket|tls.TLSSocket", "name": "connection", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>See <a href=\"#http2_response_socket\"><code>response.socket</code></a>.</p>" }, { "textRaw": "`finished` {boolean}", "type": "boolean", "name": "finished", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>Boolean value that indicates whether the response has completed. Starts\nas <code>false</code>. After <a href=\"#http2_response_end_data_encoding_callback\"><code>response.end()</code></a> executes, the value will be <code>true</code>.</p>" }, { "textRaw": "`headersSent` {boolean}", "type": "boolean", "name": "headersSent", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>True if headers were sent, false otherwise (read-only).</p>" }, { "textRaw": "`sendDate` {boolean}", "type": "boolean", "name": "sendDate", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>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.</p>\n<p>This should only be disabled for testing; HTTP requires the Date header\nin responses.</p>" }, { "textRaw": "`socket` {net.Socket|tls.TLSSocket}", "type": "net.Socket|tls.TLSSocket", "name": "socket", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>Returns a <code>Proxy</code> object that acts as a <code>net.Socket</code> (or <code>tls.TLSSocket</code>) but\napplies getters, setters, and methods based on HTTP/2 logic.</p>\n<p><code>destroyed</code>, <code>readable</code>, and <code>writable</code> properties will be retrieved from and\nset on <code>response.stream</code>.</p>\n<p><code>destroy</code>, <code>emit</code>, <code>end</code>, <code>on</code> and <code>once</code> methods will be called on\n<code>response.stream</code>.</p>\n<p><code>setTimeout</code> method will be called on <code>response.stream.session</code>.</p>\n<p><code>pause</code>, <code>read</code>, <code>resume</code>, and <code>write</code> will throw an error with code\n<code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code>. See <a href=\"#http2_http2session_and_sockets\"><code>Http2Session</code> and Sockets</a> for\nmore information.</p>\n<p>All other interactions will be routed directly to the socket.</p>\n<pre><code class=\"language-js\">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</code></pre>" }, { "textRaw": "`statusCode` {number}", "type": "number", "name": "statusCode", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>When using implicit headers (not calling <a href=\"#http2_response_writehead_statuscode_statusmessage_headers\"><code>response.writeHead()</code></a> explicitly),\nthis property controls the status code that will be sent to the client when\nthe headers get flushed.</p>\n<pre><code class=\"language-js\">response.statusCode = 404;\n</code></pre>\n<p>After response header was sent to the client, this property indicates the\nstatus code which was sent out.</p>" }, { "textRaw": "`statusMessage` {string}", "type": "string", "name": "statusMessage", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>Status message is not supported by HTTP/2 (RFC7540 8.1.2.4). It returns\nan empty string.</p>" }, { "textRaw": "`stream` {Http2Stream}", "type": "Http2Stream", "name": "stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<p>The <a href=\"#http2_class_http2stream\"><code>Http2Stream</code></a> object backing the response.</p>" } ] } ], "type": "module", "displayName": "Compatibility API" }, { "textRaw": "Collecting HTTP/2 Performance Metrics", "name": "collecting_http/2_performance_metrics", "desc": "<p>The <a href=\"perf_hooks.html\">Performance Observer</a> API can be used to collect basic performance\nmetrics for each <code>Http2Session</code> and <code>Http2Stream</code> instance.</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>The <code>entryType</code> property of the <code>PerformanceEntry</code> will be equal to <code>'http2'</code>.</p>\n<p>The <code>name</code> property of the <code>PerformanceEntry</code> will be equal to either\n<code>'Http2Stream'</code> or <code>'Http2Session'</code>.</p>\n<p>If <code>name</code> is equal to <code>Http2Stream</code>, the <code>PerformanceEntry</code> will contain the\nfollowing additional properties:</p>\n<ul>\n<li><code>bytesRead</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The number of <code>DATA</code> frame bytes received for this\n<code>Http2Stream</code>.</li>\n<li><code>bytesWritten</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The number of <code>DATA</code> frame bytes sent for this\n<code>Http2Stream</code>.</li>\n<li><code>id</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The identifier of the associated <code>Http2Stream</code></li>\n<li><code>timeToFirstByte</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The number of milliseconds elapsed between the\n<code>PerformanceEntry</code> <code>startTime</code> and the reception of the first <code>DATA</code> frame.</li>\n<li><code>timeToFirstByteSent</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The number of milliseconds elapsed between\nthe <code>PerformanceEntry</code> <code>startTime</code> and sending of the first <code>DATA</code> frame.</li>\n<li><code>timeToFirstHeader</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The number of milliseconds elapsed between the\n<code>PerformanceEntry</code> <code>startTime</code> and the reception of the first header.</li>\n</ul>\n<p>If <code>name</code> is equal to <code>Http2Session</code>, the <code>PerformanceEntry</code> will contain the\nfollowing additional properties:</p>\n<ul>\n<li><code>bytesRead</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The number of bytes received for this <code>Http2Session</code>.</li>\n<li><code>bytesWritten</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The number of bytes sent for this <code>Http2Session</code>.</li>\n<li><code>framesReceived</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The number of HTTP/2 frames received by the\n<code>Http2Session</code>.</li>\n<li><code>framesSent</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The number of HTTP/2 frames sent by the <code>Http2Session</code>.</li>\n<li><code>maxConcurrentStreams</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The maximum number of streams concurrently\nopen during the lifetime of the <code>Http2Session</code>.</li>\n<li><code>pingRTT</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The number of milliseconds elapsed since the transmission\nof a <code>PING</code> frame and the reception of its acknowledgment. Only present if\na <code>PING</code> frame has been sent on the <code>Http2Session</code>.</li>\n<li><code>streamAverageDuration</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The average duration (in milliseconds) for\nall <code>Http2Stream</code> instances.</li>\n<li><code>streamCount</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><number></a> The number of <code>Http2Stream</code> instances processed by\nthe <code>Http2Session</code>.</li>\n<li><code>type</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\"><string></a> Either <code>'server'</code> or <code>'client'</code> to identify the type of\n<code>Http2Session</code>.</li>\n</ul>", "type": "module", "displayName": "Collecting HTTP/2 Performance Metrics" } ], "type": "module", "displayName": "HTTP/2" } ] }