/
opt
/
alt
/
alt-nodejs10
/
root
/
lib
/
node_modules
/
npm
/
html
/
html
/
api
/
Upload Filee
HOME
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>HTTP/2 | Node.js v10.24.1 Documentation</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic"> <link rel="stylesheet" href="assets/style.css"> <link rel="stylesheet" href="assets/sh.css"> <link rel="canonical" href="https://nodejs.org/api/http2.html"> </head> <body class="alt apidoc" id="api-section-http2"> <div id="content" class="clearfix"> <div id="column2" class="interior"> <div id="intro" class="interior"> <a href="/" title="Go back to the home page"> Node.js </a> </div> <ul> <li><a href="documentation.html" class="nav-documentation">About these Docs</a></li> <li><a href="synopsis.html" class="nav-synopsis">Usage & Example</a></li> </ul> <div class="line"></div> <ul> <li><a href="assert.html" class="nav-assert">Assertion Testing</a></li> <li><a href="async_hooks.html" class="nav-async_hooks">Async Hooks</a></li> <li><a href="buffer.html" class="nav-buffer">Buffer</a></li> <li><a href="addons.html" class="nav-addons">C++ Addons</a></li> <li><a href="n-api.html" class="nav-n-api">C/C++ Addons - N-API</a></li> <li><a href="child_process.html" class="nav-child_process">Child Processes</a></li> <li><a href="cluster.html" class="nav-cluster">Cluster</a></li> <li><a href="cli.html" class="nav-cli">Command Line Options</a></li> <li><a href="console.html" class="nav-console">Console</a></li> <li><a href="crypto.html" class="nav-crypto">Crypto</a></li> <li><a href="debugger.html" class="nav-debugger">Debugger</a></li> <li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> <li><a href="dns.html" class="nav-dns">DNS</a></li> <li><a href="domain.html" class="nav-domain">Domain</a></li> <li><a href="esm.html" class="nav-esm">ECMAScript Modules</a></li> <li><a href="errors.html" class="nav-errors">Errors</a></li> <li><a href="events.html" class="nav-events">Events</a></li> <li><a href="fs.html" class="nav-fs">File System</a></li> <li><a href="globals.html" class="nav-globals">Globals</a></li> <li><a href="http.html" class="nav-http">HTTP</a></li> <li><a href="http2.html" class="nav-http2 active">HTTP/2</a></li> <li><a href="https.html" class="nav-https">HTTPS</a></li> <li><a href="inspector.html" class="nav-inspector">Inspector</a></li> <li><a href="intl.html" class="nav-intl">Internationalization</a></li> <li><a href="modules.html" class="nav-modules">Modules</a></li> <li><a href="net.html" class="nav-net">Net</a></li> <li><a href="os.html" class="nav-os">OS</a></li> <li><a href="path.html" class="nav-path">Path</a></li> <li><a href="perf_hooks.html" class="nav-perf_hooks">Performance Hooks</a></li> <li><a href="process.html" class="nav-process">Process</a></li> <li><a href="punycode.html" class="nav-punycode">Punycode</a></li> <li><a href="querystring.html" class="nav-querystring">Query Strings</a></li> <li><a href="readline.html" class="nav-readline">Readline</a></li> <li><a href="repl.html" class="nav-repl">REPL</a></li> <li><a href="stream.html" class="nav-stream">Stream</a></li> <li><a href="string_decoder.html" class="nav-string_decoder">String Decoder</a></li> <li><a href="timers.html" class="nav-timers">Timers</a></li> <li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> <li><a href="tracing.html" class="nav-tracing">Trace Events</a></li> <li><a href="tty.html" class="nav-tty">TTY</a></li> <li><a href="dgram.html" class="nav-dgram">UDP/Datagram</a></li> <li><a href="url.html" class="nav-url">URL</a></li> <li><a href="util.html" class="nav-util">Utilities</a></li> <li><a href="v8.html" class="nav-v8">V8</a></li> <li><a href="vm.html" class="nav-vm">VM</a></li> <li><a href="worker_threads.html" class="nav-worker_threads">Worker Threads</a></li> <li><a href="zlib.html" class="nav-zlib">Zlib</a></li> </ul> <div class="line"></div> <ul> <li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">GitHub Repo & Issue Tracker</a></li> </ul> </div> <div id="column1" data-id="http2" class="interior"> <header> <h1>Node.js v10.24.1 Documentation</h1> <div id="gtoc"> <ul> <li> <a href="index.html" name="toc">Index</a> </li> <li> <a href="all.html">View on single page</a> </li> <li> <a href="http2.json">View as JSON</a> </li> <li class="version-picker"> <a href="#">View another version <span>▼</span></a> <ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v15.x/api/http2.html">15.x</a></li> <li><a href="https://nodejs.org/docs/latest-v14.x/api/http2.html">14.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v13.x/api/http2.html">13.x</a></li> <li><a href="https://nodejs.org/docs/latest-v12.x/api/http2.html">12.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v11.x/api/http2.html">11.x</a></li> <li><a href="https://nodejs.org/docs/latest-v10.x/api/http2.html">10.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v9.x/api/http2.html">9.x</a></li> <li><a href="https://nodejs.org/docs/latest-v8.x/api/http2.html">8.x</a></li></ol> </li> <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/master/doc/api/http2.md"><span class="github_icon"><svg height="16" width="16" viewBox="0 0 16.1 16.1" fill="currentColor"><path d="M8 0a8 8 0 0 0-2.5 15.6c.4 0 .5-.2.5-.4v-1.5c-2 .4-2.5-.5-2.7-1 0-.1-.5-.9-.8-1-.3-.2-.7-.6 0-.6.6 0 1 .6 1.2.8.7 1.2 1.9 1 2.4.7 0-.5.2-.9.5-1-1.8-.3-3.7-1-3.7-4 0-.9.3-1.6.8-2.2 0-.2-.3-1 .1-2 0 0 .7-.3 2.2.7a7.4 7.4 0 0 1 4 0c1.5-1 2.2-.8 2.2-.8.5 1.1.2 2 .1 2.1.5.6.8 1.3.8 2.2 0 3-1.9 3.7-3.6 4 .3.2.5.7.5 1.4v2.2c0 .2.1.5.5.4A8 8 0 0 0 16 8a8 8 0 0 0-8-8z"/></svg></span>Edit on GitHub</a></li> </ul> </div> <hr> </header> <div id="toc"> <h2>Table of Contents</h2> <ul> <li> <p><span class="stability_2"><a href="#http2_http_2">HTTP/2</a></span></p> <ul> <li> <p><a href="#http2_core_api">Core API</a></p> <ul> <li><a href="#http2_server_side_example">Server-side example</a></li> <li><a href="#http2_client_side_example">Client-side example</a></li> <li> <p><a href="#http2_class_http2session">Class: Http2Session</a></p> <ul> <li><a href="#http2_http2session_and_sockets">Http2Session and Sockets</a></li> <li><a href="#http2_event_close">Event: 'close'</a></li> <li><a href="#http2_event_connect">Event: 'connect'</a></li> <li><a href="#http2_event_error">Event: 'error'</a></li> <li><a href="#http2_event_frameerror">Event: 'frameError'</a></li> <li><a href="#http2_event_goaway">Event: 'goaway'</a></li> <li><a href="#http2_event_localsettings">Event: 'localSettings'</a></li> <li><a href="#http2_event_ping">Event: 'ping'</a></li> <li><a href="#http2_event_remotesettings">Event: 'remoteSettings'</a></li> <li><a href="#http2_event_stream">Event: 'stream'</a></li> <li><a href="#http2_event_timeout">Event: 'timeout'</a></li> <li><a href="#http2_http2session_alpnprotocol">http2session.alpnProtocol</a></li> <li><a href="#http2_http2session_close_callback">http2session.close([callback])</a></li> <li><a href="#http2_http2session_closed">http2session.closed</a></li> <li><a href="#http2_http2session_connecting">http2session.connecting</a></li> <li><a href="#http2_http2session_destroy_error_code">http2session.destroy([error][, code])</a></li> <li><a href="#http2_http2session_destroyed">http2session.destroyed</a></li> <li><a href="#http2_http2session_encrypted">http2session.encrypted</a></li> <li><a href="#http2_http2session_goaway_code_laststreamid_opaquedata">http2session.goaway([code[, lastStreamID[, opaqueData]]])</a></li> <li><a href="#http2_http2session_localsettings">http2session.localSettings</a></li> <li><a href="#http2_http2session_originset">http2session.originSet</a></li> <li><a href="#http2_http2session_pendingsettingsack">http2session.pendingSettingsAck</a></li> <li><a href="#http2_http2session_ping_payload_callback">http2session.ping([payload, ]callback)</a></li> <li><a href="#http2_http2session_ref">http2session.ref()</a></li> <li><a href="#http2_http2session_remotesettings">http2session.remoteSettings</a></li> <li><a href="#http2_http2session_settimeout_msecs_callback">http2session.setTimeout(msecs, callback)</a></li> <li><a href="#http2_http2session_socket">http2session.socket</a></li> <li><a href="#http2_http2session_state">http2session.state</a></li> <li><a href="#http2_http2session_settings_settings">http2session.settings(settings)</a></li> <li><a href="#http2_http2session_type">http2session.type</a></li> <li><a href="#http2_http2session_unref">http2session.unref()</a></li> </ul> </li> <li> <p><a href="#http2_class_serverhttp2session">Class: ServerHttp2Session</a></p> <ul> <li><a href="#http2_serverhttp2session_altsvc_alt_originorstream">serverhttp2session.altsvc(alt, originOrStream)</a></li> <li><a href="#http2_specifying_alternative_services">Specifying alternative services</a></li> <li><a href="#http2_serverhttp2session_origin_origins">serverhttp2session.origin(...origins)</a></li> </ul> </li> <li> <p><a href="#http2_class_clienthttp2session">Class: ClientHttp2Session</a></p> <ul> <li><a href="#http2_event_altsvc">Event: 'altsvc'</a></li> <li><a href="#http2_event_origin">Event: 'origin'</a></li> <li><a href="#http2_clienthttp2session_request_headers_options">clienthttp2session.request(headers[, options])</a></li> </ul> </li> <li> <p><a href="#http2_class_http2stream">Class: Http2Stream</a></p> <ul> <li> <p><a href="#http2_http2stream_lifecycle">Http2Stream Lifecycle</a></p> <ul> <li><a href="#http2_creation">Creation</a></li> <li><a href="#http2_destruction">Destruction</a></li> </ul> </li> <li><a href="#http2_event_aborted">Event: 'aborted'</a></li> <li><a href="#http2_event_close_1">Event: 'close'</a></li> <li><a href="#http2_event_error_1">Event: 'error'</a></li> <li><a href="#http2_event_frameerror_1">Event: 'frameError'</a></li> <li><a href="#http2_event_timeout_1">Event: 'timeout'</a></li> <li><a href="#http2_event_trailers">Event: 'trailers'</a></li> <li><a href="#http2_event_wanttrailers">Event: 'wantTrailers'</a></li> <li><a href="#http2_http2stream_aborted">http2stream.aborted</a></li> <li><a href="#http2_http2stream_buffersize">http2stream.bufferSize</a></li> <li><a href="#http2_http2stream_close_code_callback">http2stream.close(code[, callback])</a></li> <li><a href="#http2_http2stream_closed">http2stream.closed</a></li> <li><a href="#http2_http2stream_destroyed">http2stream.destroyed</a></li> <li><a href="#http2_http2stream_endafterheaders">http2stream.endAfterHeaders</a></li> <li><a href="#http2_http2stream_pending">http2stream.pending</a></li> <li><a href="#http2_http2stream_priority_options">http2stream.priority(options)</a></li> <li><a href="#http2_http2stream_rstcode">http2stream.rstCode</a></li> <li><a href="#http2_http2stream_sentheaders">http2stream.sentHeaders</a></li> <li><a href="#http2_http2stream_sentinfoheaders">http2stream.sentInfoHeaders</a></li> <li><a href="#http2_http2stream_senttrailers">http2stream.sentTrailers</a></li> <li><a href="#http2_http2stream_session">http2stream.session</a></li> <li><a href="#http2_http2stream_settimeout_msecs_callback">http2stream.setTimeout(msecs, callback)</a></li> <li><a href="#http2_http2stream_state">http2stream.state</a></li> <li><a href="#http2_http2stream_sendtrailers_headers">http2stream.sendTrailers(headers)</a></li> </ul> </li> <li> <p><a href="#http2_class_clienthttp2stream">Class: ClientHttp2Stream</a></p> <ul> <li><a href="#http2_event_continue">Event: 'continue'</a></li> <li><a href="#http2_event_headers">Event: 'headers'</a></li> <li><a href="#http2_event_push">Event: 'push'</a></li> <li><a href="#http2_event_response">Event: 'response'</a></li> </ul> </li> <li> <p><a href="#http2_class_serverhttp2stream">Class: ServerHttp2Stream</a></p> <ul> <li><a href="#http2_http2stream_additionalheaders_headers">http2stream.additionalHeaders(headers)</a></li> <li><a href="#http2_http2stream_headerssent">http2stream.headersSent</a></li> <li><a href="#http2_http2stream_pushallowed">http2stream.pushAllowed</a></li> <li><a href="#http2_http2stream_pushstream_headers_options_callback">http2stream.pushStream(headers[, options], callback)</a></li> <li><a href="#http2_http2stream_respond_headers_options">http2stream.respond([headers[, options]])</a></li> <li><a href="#http2_http2stream_respondwithfd_fd_headers_options">http2stream.respondWithFD(fd[, headers[, options]])</a></li> <li><a href="#http2_http2stream_respondwithfile_path_headers_options">http2stream.respondWithFile(path[, headers[, options]])</a></li> </ul> </li> <li> <p><a href="#http2_class_http2server">Class: Http2Server</a></p> <ul> <li><a href="#http2_event_checkcontinue">Event: 'checkContinue'</a></li> <li><a href="#http2_event_request">Event: 'request'</a></li> <li><a href="#http2_event_session">Event: 'session'</a></li> <li><a href="#http2_event_sessionerror">Event: 'sessionError'</a></li> <li><a href="#http2_event_stream_1">Event: 'stream'</a></li> <li><a href="#http2_event_timeout_2">Event: 'timeout'</a></li> <li><a href="#http2_server_close_callback">server.close([callback])</a></li> <li><a href="#http2_server_settimeout_msecs_callback">server.setTimeout([msecs][, callback])</a></li> </ul> </li> <li> <p><a href="#http2_class_http2secureserver">Class: Http2SecureServer</a></p> <ul> <li><a href="#http2_event_checkcontinue_1">Event: 'checkContinue'</a></li> <li><a href="#http2_event_request_1">Event: 'request'</a></li> <li><a href="#http2_event_session_1">Event: 'session'</a></li> <li><a href="#http2_event_sessionerror_1">Event: 'sessionError'</a></li> <li><a href="#http2_event_stream_2">Event: 'stream'</a></li> <li><a href="#http2_event_timeout_3">Event: 'timeout'</a></li> <li><a href="#http2_event_unknownprotocol">Event: 'unknownProtocol'</a></li> <li><a href="#http2_server_close_callback_1">server.close([callback])</a></li> <li><a href="#http2_server_settimeout_msecs_callback_1">server.setTimeout([msecs][, callback])</a></li> </ul> </li> <li><a href="#http2_http2_createserver_options_onrequesthandler">http2.createServer(options[, onRequestHandler])</a></li> <li><a href="#http2_http2_createsecureserver_options_onrequesthandler">http2.createSecureServer(options[, onRequestHandler])</a></li> <li><a href="#http2_http2_connect_authority_options_listener">http2.connect(authority[, options][, listener])</a></li> <li> <p><a href="#http2_http2_constants">http2.constants</a></p> <ul> <li><a href="#http2_error_codes_for_rst_stream_and_goaway">Error Codes for RST_STREAM and GOAWAY</a></li> </ul> </li> <li><a href="#http2_http2_getdefaultsettings">http2.getDefaultSettings()</a></li> <li><a href="#http2_http2_getpackedsettings_settings">http2.getPackedSettings(settings)</a></li> <li><a href="#http2_http2_getunpackedsettings_buf">http2.getUnpackedSettings(buf)</a></li> <li><a href="#http2_headers_object">Headers Object</a></li> <li><a href="#http2_settings_object">Settings Object</a></li> <li><a href="#http2_using_options_selectpadding">Using <code>options.selectPadding()</code></a></li> <li><a href="#http2_error_handling">Error Handling</a></li> <li><a href="#http2_invalid_character_handling_in_header_names_and_values">Invalid character handling in header names and values</a></li> <li><a href="#http2_push_streams_on_the_client">Push streams on the client</a></li> <li><a href="#http2_supporting_the_connect_method">Supporting the CONNECT method</a></li> <li><a href="#http2_the_extended_connect_protocol">The Extended CONNECT Protocol</a></li> </ul> </li> <li> <p><a href="#http2_compatibility_api">Compatibility API</a></p> <ul> <li><a href="#http2_alpn_negotiation">ALPN negotiation</a></li> <li> <p><a href="#http2_class_http2_http2serverrequest">Class: http2.Http2ServerRequest</a></p> <ul> <li><a href="#http2_event_aborted_1">Event: 'aborted'</a></li> <li><a href="#http2_event_close_2">Event: 'close'</a></li> <li><a href="#http2_request_aborted">request.aborted</a></li> <li><a href="#http2_request_authority">request.authority</a></li> <li><a href="#http2_request_destroy_error">request.destroy([error])</a></li> <li><a href="#http2_request_headers">request.headers</a></li> <li><a href="#http2_request_httpversion">request.httpVersion</a></li> <li><a href="#http2_request_method">request.method</a></li> <li><a href="#http2_request_rawheaders">request.rawHeaders</a></li> <li><a href="#http2_request_rawtrailers">request.rawTrailers</a></li> <li><a href="#http2_request_scheme">request.scheme</a></li> <li><a href="#http2_request_settimeout_msecs_callback">request.setTimeout(msecs, callback)</a></li> <li><a href="#http2_request_socket">request.socket</a></li> <li><a href="#http2_request_stream">request.stream</a></li> <li><a href="#http2_request_trailers">request.trailers</a></li> <li><a href="#http2_request_url">request.url</a></li> </ul> </li> <li> <p><a href="#http2_class_http2_http2serverresponse">Class: http2.Http2ServerResponse</a></p> <ul> <li><a href="#http2_event_close_3">Event: 'close'</a></li> <li><a href="#http2_event_finish">Event: 'finish'</a></li> <li><a href="#http2_response_addtrailers_headers">response.addTrailers(headers)</a></li> <li><a href="#http2_response_connection">response.connection</a></li> <li><a href="#http2_response_end_data_encoding_callback">response.end([data][, encoding][, callback])</a></li> <li><a href="#http2_response_finished">response.finished</a></li> <li><a href="#http2_response_getheader_name">response.getHeader(name)</a></li> <li><a href="#http2_response_getheadernames">response.getHeaderNames()</a></li> <li><a href="#http2_response_getheaders">response.getHeaders()</a></li> <li><a href="#http2_response_hasheader_name">response.hasHeader(name)</a></li> <li><a href="#http2_response_headerssent">response.headersSent</a></li> <li><a href="#http2_response_removeheader_name">response.removeHeader(name)</a></li> <li><a href="#http2_response_senddate">response.sendDate</a></li> <li><a href="#http2_response_setheader_name_value">response.setHeader(name, value)</a></li> <li><a href="#http2_response_settimeout_msecs_callback">response.setTimeout(msecs[, callback])</a></li> <li><a href="#http2_response_socket">response.socket</a></li> <li><a href="#http2_response_statuscode">response.statusCode</a></li> <li><a href="#http2_response_statusmessage">response.statusMessage</a></li> <li><a href="#http2_response_stream">response.stream</a></li> <li><a href="#http2_response_write_chunk_encoding_callback">response.write(chunk[, encoding][, callback])</a></li> <li><a href="#http2_response_writecontinue">response.writeContinue()</a></li> <li><a href="#http2_response_writehead_statuscode_statusmessage_headers">response.writeHead(statusCode[, statusMessage][, headers])</a></li> <li><a href="#http2_response_createpushresponse_headers_callback">response.createPushResponse(headers, callback)</a></li> </ul> </li> </ul> </li> <li><a href="#http2_collecting_http_2_performance_metrics">Collecting HTTP/2 Performance Metrics</a></li> </ul> </li> </ul> </div> <div id="apicontent"> <h1>HTTP/2<span><a class="mark" href="#http2_http_2" id="http2_http_2">#</a></span></h1> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.10.0</td> <td><p>HTTP/2 is now Stable. Previously, it had been Experimental.</p></td></tr> <tr><td>v8.4.0</td> <td><p><span>Added in: v8.4.0</span></p></td></tr> </tbody></table> </details> </div> <p></p><div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>http2</code> module provides an implementation of the <a href="https://tools.ietf.org/html/rfc7540">HTTP/2</a> protocol. It can be accessed using:</p> <pre><code class="language-js">const http2 = require('http2'); </code></pre> <h2>Core API<span><a class="mark" href="#http2_core_api" id="http2_core_api">#</a></span></h2> <p>The Core API provides a low-level interface designed specifically around support for HTTP/2 protocol features. It is specifically <em>not</em> designed for compatibility with the existing <a href="http.html">HTTP/1</a> module API. However, the <a href="#http2_compatibility_api">Compatibility API</a> is.</p> <p>The <code>http2</code> Core API is much more symmetric between client and server than the <code>http</code> API. For instance, most events, like <code>'error'</code>, <code>'connect'</code> and <code>'stream'</code>, can be emitted either by client-side code or server-side code.</p> <h3>Server-side example<span><a class="mark" href="#http2_server_side_example" id="http2_server_side_example">#</a></span></h3> <p>The following illustrates a simple HTTP/2 server using the Core API. Since there are no browsers known that support <a href="https://http2.github.io/faq/#does-http2-require-encryption">unencrypted HTTP/2</a>, the use of <a href="#http2_http2_createsecureserver_options_onrequesthandler"><code>http2.createSecureServer()</code></a> is necessary when communicating with browser clients.</p> <pre><code class="language-js">const http2 = require('http2'); const fs = require('fs'); const server = http2.createSecureServer({ key: fs.readFileSync('localhost-privkey.pem'), cert: fs.readFileSync('localhost-cert.pem') }); server.on('error', (err) => console.error(err)); server.on('stream', (stream, headers) => { // stream is a Duplex stream.respond({ 'content-type': 'text/html', ':status': 200 }); stream.end('<h1>Hello World</h1>'); }); server.listen(8443); </code></pre> <p>To generate the certificate and key for this example, run:</p> <pre><code class="language-bash">openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \ -keyout localhost-privkey.pem -out localhost-cert.pem </code></pre> <h3>Client-side example<span><a class="mark" href="#http2_client_side_example" id="http2_client_side_example">#</a></span></h3> <p>The following illustrates an HTTP/2 client:</p> <pre><code class="language-js">const http2 = require('http2'); const fs = require('fs'); const client = http2.connect('https://localhost:8443', { ca: fs.readFileSync('localhost-cert.pem') }); client.on('error', (err) => console.error(err)); const req = client.request({ ':path': '/' }); req.on('response', (headers, flags) => { for (const name in headers) { console.log(`${name}: ${headers[name]}`); } }); req.setEncoding('utf8'); let data = ''; req.on('data', (chunk) => { data += chunk; }); req.on('end', () => { console.log(`\n${data}`); client.close(); }); req.end(); </code></pre> <h3>Class: Http2Session<span><a class="mark" href="#http2_class_http2session" id="http2_class_http2session">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li>Extends: <a href="events.html#events_class_eventemitter" class="type"><EventEmitter></a></li> </ul> <p>Instances of the <code>http2.Http2Session</code> class represent an active communications session between an HTTP/2 client and server. Instances of this class are <em>not</em> intended to be constructed directly by user code.</p> <p>Each <code>Http2Session</code> instance will exhibit slightly different behaviors depending on whether it is operating as a server or a client. The <code>http2session.type</code> property can be used to determine the mode in which an <code>Http2Session</code> is operating. On the server side, user code should rarely have occasion to work with the <code>Http2Session</code> object directly, with most actions typically taken through interactions with either the <code>Http2Server</code> or <code>Http2Stream</code> objects.</p> <p>User code will not create <code>Http2Session</code> instances directly. Server-side <code>Http2Session</code> instances are created by the <code>Http2Server</code> instance when a new HTTP/2 connection is received. Client-side <code>Http2Session</code> instances are created using the <code>http2.connect()</code> method.</p> <h4>Http2Session and Sockets<span><a class="mark" href="#http2_http2session_and_sockets" id="http2_http2session_and_sockets">#</a></span></h4> <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 <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 <code>Http2Session</code> are destroyed, both will be destroyed.</p> <p>Because of the specific serialization and processing requirements imposed by the HTTP/2 protocol, it is not recommended for user code to read data from or write data to a <code>Socket</code> instance bound to a <code>Http2Session</code>. Doing so can put the HTTP/2 session into an indeterminate state causing the session and the socket to become unusable.</p> <p>Once a <code>Socket</code> has been bound to an <code>Http2Session</code>, user code should rely solely on the API of the <code>Http2Session</code>.</p> <h4>Event: 'close'<span><a class="mark" href="#http2_event_close" id="http2_event_close">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'close'</code> event is emitted once the <code>Http2Session</code> has been destroyed. Its listener does not expect any arguments.</p> <h4>Event: 'connect'<span><a class="mark" href="#http2_event_connect" id="http2_event_connect">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>session</code> <a href="http2.html#http2_class_http2session" class="type"><Http2Session></a></li> <li><code>socket</code> <a href="net.html#net_class_net_socket" class="type"><net.Socket></a></li> </ul> <p>The <code>'connect'</code> event is emitted once the <code>Http2Session</code> has been successfully connected to the remote peer and communication may begin.</p> <p>User code will typically not listen for this event directly.</p> <h4>Event: 'error'<span><a class="mark" href="#http2_event_error" id="http2_event_error">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>The <code>'error'</code> event is emitted when an error occurs during the processing of an <code>Http2Session</code>.</p> <h4>Event: 'frameError'<span><a class="mark" href="#http2_event_frameerror" id="http2_event_frameerror">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The frame type.</li> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The error code.</li> <li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The stream id (or <code>0</code> if the frame isn't associated with a stream).</li> </ul> <p>The <code>'frameError'</code> event is emitted when an error occurs while attempting to send a frame on the session. If the frame that could not be sent is associated with a specific <code>Http2Stream</code>, an attempt to emit <code>'frameError'</code> event on the <code>Http2Stream</code> is made.</p> <p>If the <code>'frameError'</code> event is associated with a stream, the stream will be closed and destroyed immediately following the <code>'frameError'</code> event. If the event is not associated with a stream, the <code>Http2Session</code> will be shut down immediately following the <code>'frameError'</code> event.</p> <h4>Event: 'goaway'<span><a class="mark" href="#http2_event_goaway" id="http2_event_goaway">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>errorCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The HTTP/2 error code specified in the <code>GOAWAY</code> frame.</li> <li><code>lastStreamID</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The ID of the last stream the remote peer successfully processed (or <code>0</code> if no ID is specified).</li> <li><code>opaqueData</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> If additional opaque data was included in the <code>GOAWAY</code> frame, a <code>Buffer</code> instance will be passed containing that data.</li> </ul> <p>The <code>'goaway'</code> event is emitted when a <code>GOAWAY</code> frame is received.</p> <p>The <code>Http2Session</code> instance will be shut down automatically when the <code>'goaway'</code> event is emitted.</p> <h4>Event: 'localSettings'<span><a class="mark" href="#http2_event_localsettings" id="http2_event_localsettings">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>settings</code> <a href="http2.html#http2_settings_object" class="type"><HTTP/2 Settings Object></a> A copy of the <code>SETTINGS</code> frame received.</li> </ul> <p>The <code>'localSettings'</code> event is emitted when an acknowledgment <code>SETTINGS</code> frame has been received.</p> <p>When using <code>http2session.settings()</code> to submit new settings, the modified settings do not take effect until the <code>'localSettings'</code> event is emitted.</p> <pre><code class="language-js">session.settings({ enablePush: false }); session.on('localSettings', (settings) => { /* Use the new settings */ }); </code></pre> <h4>Event: 'ping'<span><a class="mark" href="#http2_event_ping" id="http2_event_ping">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.12.0</span> </div> <ul> <li><code>payload</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> The <code>PING</code> frame 8-byte payload</li> </ul> <p>The <code>'ping'</code> event is emitted whenever a <code>PING</code> frame is received from the connected peer.</p> <h4>Event: 'remoteSettings'<span><a class="mark" href="#http2_event_remotesettings" id="http2_event_remotesettings">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>settings</code> <a href="http2.html#http2_settings_object" class="type"><HTTP/2 Settings Object></a> A copy of the <code>SETTINGS</code> frame received.</li> </ul> <p>The <code>'remoteSettings'</code> event is emitted when a new <code>SETTINGS</code> frame is received from the connected peer.</p> <pre><code class="language-js">session.on('remoteSettings', (settings) => { /* Use the new settings */ }); </code></pre> <h4>Event: 'stream'<span><a class="mark" href="#http2_event_stream" id="http2_event_stream">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>stream</code> <a href="http2.html#http2_class_http2stream" class="type"><Http2Stream></a> A reference to the stream</li> <li><code>headers</code> <a href="http2.html#http2_headers_object" class="type"><HTTP/2 Headers Object></a> An object describing the headers</li> <li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The associated numeric flags</li> <li><code>rawHeaders</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An array containing the raw header names followed by their respective values.</li> </ul> <p>The <code>'stream'</code> event is emitted when a new <code>Http2Stream</code> is created.</p> <pre><code class="language-js">const http2 = require('http2'); session.on('stream', (stream, headers, flags) => { const method = headers[':method']; const path = headers[':path']; // ... stream.respond({ ':status': 200, 'content-type': 'text/plain' }); stream.write('hello '); stream.end('world'); }); </code></pre> <p>On the server side, user code will typically not listen for this event directly, and would instead register a handler for the <code>'stream'</code> event emitted by the <code>net.Server</code> or <code>tls.Server</code> instances returned by <code>http2.createServer()</code> and <code>http2.createSecureServer()</code>, respectively, as in the example below:</p> <pre><code class="language-js">const http2 = require('http2'); // Create an unencrypted HTTP/2 server const server = http2.createServer(); server.on('stream', (stream, headers) => { stream.respond({ 'content-type': 'text/html', ':status': 200 }); stream.on('error', (error) => console.error(error)); stream.end('<h1>Hello World</h1>'); }); server.listen(80); </code></pre> <p>Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence, a network error will destroy each individual stream and must be handled on the stream level, as shown above.</p> <h4>Event: 'timeout'<span><a class="mark" href="#http2_event_timeout" id="http2_event_timeout">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>After the <code>http2session.setTimeout()</code> method is used to set the timeout period for this <code>Http2Session</code>, the <code>'timeout'</code> event is emitted if there is no activity on the <code>Http2Session</code> after the configured number of milliseconds.</p> <pre><code class="language-js">session.setTimeout(2000); session.on('timeout', () => { /* .. */ }); </code></pre> <h4>http2session.alpnProtocol<span><a class="mark" href="#http2_http2session_alpnprotocol" id="http2_http2session_alpnprotocol">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li> </ul> <p>Value will be <code>undefined</code> if the <code>Http2Session</code> is not yet connected to a socket, <code>h2c</code> if the <code>Http2Session</code> is not connected to a <code>TLSSocket</code>, or will return the value of the connected <code>TLSSocket</code>'s own <code>alpnProtocol</code> property.</p> <h4>http2session.close([callback])<span><a class="mark" href="#http2_http2session_close_callback" id="http2_http2session_close_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Gracefully closes the <code>Http2Session</code>, allowing any existing streams to complete on their own and preventing new <code>Http2Stream</code> instances from being created. Once closed, <code>http2session.destroy()</code> <em>might</em> be called if there are no open <code>Http2Stream</code> instances.</p> <p>If specified, the <code>callback</code> function is registered as a handler for the <code>'close'</code> event.</p> <h4>http2session.closed<span><a class="mark" href="#http2_http2session_closed" id="http2_http2session_closed">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Will be <code>true</code> if this <code>Http2Session</code> instance has been closed, otherwise <code>false</code>.</p> <h4>http2session.connecting<span><a class="mark" href="#http2_http2session_connecting" id="http2_http2session_connecting">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Will be <code>true</code> if this <code>Http2Session</code> instance is still connecting, will be set to <code>false</code> before emitting <code>connect</code> event and/or calling the <code>http2.connect</code> callback.</p> <h4>http2session.destroy([error][, code])<span><a class="mark" href="#http2_http2session_destroy_error_code" id="http2_http2session_destroy_error_code">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> An <code>Error</code> object if the <code>Http2Session</code> is being destroyed due to an error.</li> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The HTTP/2 error code to send in the final <code>GOAWAY</code> frame. If unspecified, and <code>error</code> is not undefined, the default is <code>INTERNAL_ERROR</code>, otherwise defaults to <code>NO_ERROR</code>.</li> </ul> <p>Immediately terminates the <code>Http2Session</code> and the associated <code>net.Socket</code> or <code>tls.TLSSocket</code>.</p> <p>Once destroyed, the <code>Http2Session</code> will emit the <code>'close'</code> event. If <code>error</code> is not undefined, an <code>'error'</code> event will be emitted immediately before the <code>'close'</code> event.</p> <p>If there are any remaining open <code>Http2Streams</code> associated with the <code>Http2Session</code>, those will also be destroyed.</p> <h4>http2session.destroyed<span><a class="mark" href="#http2_http2session_destroyed" id="http2_http2session_destroyed">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Will be <code>true</code> if this <code>Http2Session</code> instance has been destroyed and must no longer be used, otherwise <code>false</code>.</p> <h4>http2session.encrypted<span><a class="mark" href="#http2_http2session_encrypted" id="http2_http2session_encrypted">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li> </ul> <p>Value is <code>undefined</code> if the <code>Http2Session</code> session socket has not yet been connected, <code>true</code> if the <code>Http2Session</code> is connected with a <code>TLSSocket</code>, and <code>false</code> if the <code>Http2Session</code> is connected to any other kind of socket or stream.</p> <h4>http2session.goaway([code[, lastStreamID[, opaqueData]]])<span><a class="mark" href="#http2_http2session_goaway_code_laststreamid_opaquedata" id="http2_http2session_goaway_code_laststreamid_opaquedata">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> An HTTP/2 error code</li> <li><code>lastStreamID</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 last processed <code>Http2Stream</code></li> <li><code>opaqueData</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> A <code>TypedArray</code> or <code>DataView</code> instance containing additional data to be carried within the <code>GOAWAY</code> frame.</li> </ul> <p>Transmits a <code>GOAWAY</code> frame to the connected peer <em>without</em> shutting down the <code>Http2Session</code>.</p> <h4>http2session.localSettings<span><a class="mark" href="#http2_http2session_localsettings" id="http2_http2session_localsettings">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="http2.html#http2_settings_object" class="type"><HTTP/2 Settings Object></a></li> </ul> <p>A prototype-less object describing the current local settings of this <code>Http2Session</code>. The local settings are local to <em>this</em> <code>Http2Session</code> instance.</p> <h4>http2session.originSet<span><a class="mark" href="#http2_http2session_originset" id="http2_http2session_originset">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li> </ul> <p>If the <code>Http2Session</code> is connected to a <code>TLSSocket</code>, the <code>originSet</code> property will return an <code>Array</code> of origins for which the <code>Http2Session</code> may be considered authoritative.</p> <p>The <code>originSet</code> property is only available when using a secure TLS connection.</p> <h4>http2session.pendingSettingsAck<span><a class="mark" href="#http2_http2session_pendingsettingsack" id="http2_http2session_pendingsettingsack">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Indicates whether or not the <code>Http2Session</code> is currently waiting for an acknowledgment for a sent <code>SETTINGS</code> frame. Will be <code>true</code> after calling the <code>http2session.settings()</code> method. Will be <code>false</code> once all sent SETTINGS frames have been acknowledged.</p> <h4>http2session.ping([payload, ]callback)<span><a class="mark" href="#http2_http2session_ping_payload_callback" id="http2_http2session_ping_payload_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.9.3</span> </div> <ul> <li><code>payload</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> Optional ping payload.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Sends a <code>PING</code> frame to the connected HTTP/2 peer. A <code>callback</code> function must be provided. The method will return <code>true</code> if the <code>PING</code> was sent, <code>false</code> otherwise.</p> <p>The maximum number of outstanding (unacknowledged) pings is determined by the <code>maxOutstandingPings</code> configuration option. The default maximum is 10.</p> <p>If provided, the <code>payload</code> must be a <code>Buffer</code>, <code>TypedArray</code>, or <code>DataView</code> containing 8 bytes of data that will be transmitted with the <code>PING</code> and returned with the ping acknowledgment.</p> <p>The callback will be invoked with three arguments: an error argument that will be <code>null</code> if the <code>PING</code> was successfully acknowledged, a <code>duration</code> argument that reports the number of milliseconds elapsed since the ping was sent and the acknowledgment was received, and a <code>Buffer</code> containing the 8-byte <code>PING</code> payload.</p> <pre><code class="language-js">session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { if (!err) { console.log(`Ping acknowledged in ${duration} milliseconds`); console.log(`With payload '${payload.toString()}'`); } }); </code></pre> <p>If the <code>payload</code> argument is not specified, the default payload will be the 64-bit timestamp (little endian) marking the start of the <code>PING</code> duration.</p> <h4>http2session.ref()<span><a class="mark" href="#http2_http2session_ref" id="http2_http2session_ref">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <p>Calls <a href="net.html#net_socket_ref"><code>ref()</code></a> on this <code>Http2Session</code> instance's underlying <a href="net.html#net_class_net_socket"><code>net.Socket</code></a>.</p> <h4>http2session.remoteSettings<span><a class="mark" href="#http2_http2session_remotesettings" id="http2_http2session_remotesettings">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="http2.html#http2_settings_object" class="type"><HTTP/2 Settings Object></a></li> </ul> <p>A prototype-less object describing the current remote settings of this <code>Http2Session</code>. The remote settings are set by the <em>connected</em> HTTP/2 peer.</p> <h4>http2session.setTimeout(msecs, callback)<span><a class="mark" href="#http2_http2session_settimeout_msecs_callback" id="http2_http2session_settimeout_msecs_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Used to set a callback function that is called when there is no activity on the <code>Http2Session</code> after <code>msecs</code> milliseconds. The given <code>callback</code> is registered as a listener on the <code>'timeout'</code> event.</p> <h4>http2session.socket<span><a class="mark" href="#http2_http2session_socket" id="http2_http2session_socket">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="net.html#net_class_net_socket" class="type"><net.Socket></a> | <a href="tls.html#tls_class_tls_tlssocket" class="type"><tls.TLSSocket></a></li> </ul> <p>Returns a <code>Proxy</code> object that acts as a <code>net.Socket</code> (or <code>tls.TLSSocket</code>) but limits available methods to ones safe to use with HTTP/2.</p> <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 an error with code <code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code>. See <a href="#http2_http2session_and_sockets"><code>Http2Session</code> and Sockets</a> for more information.</p> <p><code>setTimeout</code> method will be called on this <code>Http2Session</code>.</p> <p>All other interactions will be routed directly to the socket.</p> <h4>http2session.state<span><a class="mark" href="#http2_http2session_state" id="http2_http2session_state">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>Provides miscellaneous information about the current state of the <code>Http2Session</code>.</p> <ul> <li> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <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) flow control window size for the <code>Http2Session</code>.</li> <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 that have been received since the last flow control <code>WINDOW_UPDATE</code>.</li> <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 next time a new <code>Http2Stream</code> is created by this <code>Http2Session</code>.</li> <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 send without receiving a <code>WINDOW_UPDATE</code>.</li> <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> for which a <code>HEADERS</code> or <code>DATA</code> frame was most recently received.</li> <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> may send without receiving a <code>WINDOW_UPDATE</code>.</li> <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 outbound queue for this <code>Http2Session</code>.</li> <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 outbound header compression state table.</li> <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 inbound header compression state table.</li> </ul> </li> </ul> <p>An object describing the current status of this <code>Http2Session</code>.</p> <h4>http2session.settings(settings)<span><a class="mark" href="#http2_http2session_settings_settings" id="http2_http2session_settings_settings">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>settings</code> <a href="http2.html#http2_settings_object" class="type"><HTTP/2 Settings Object></a></li> </ul> <p>Updates the current local settings for this <code>Http2Session</code> and sends a new <code>SETTINGS</code> frame to the connected HTTP/2 peer.</p> <p>Once called, the <code>http2session.pendingSettingsAck</code> property will be <code>true</code> while the session is waiting for the remote peer to acknowledge the new settings.</p> <p>The new settings will not become effective until the <code>SETTINGS</code> acknowledgment is received and the <code>'localSettings'</code> event is emitted. It is possible to send multiple <code>SETTINGS</code> frames while acknowledgment is still pending.</p> <h4>http2session.type<span><a class="mark" href="#http2_http2session_type" id="http2_http2session_type">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The <code>http2session.type</code> will be equal to <code>http2.constants.NGHTTP2_SESSION_SERVER</code> if this <code>Http2Session</code> instance is a server, and <code>http2.constants.NGHTTP2_SESSION_CLIENT</code> if the instance is a client.</p> <h4>http2session.unref()<span><a class="mark" href="#http2_http2session_unref" id="http2_http2session_unref">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <p>Calls <a href="net.html#net_socket_unref"><code>unref()</code></a> on this <code>Http2Session</code> instance's underlying <a href="net.html#net_class_net_socket"><code>net.Socket</code></a>.</p> <h3>Class: ServerHttp2Session<span><a class="mark" href="#http2_class_serverhttp2session" id="http2_class_serverhttp2session">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <h4>serverhttp2session.altsvc(alt, originOrStream)<span><a class="mark" href="#http2_serverhttp2session_altsvc_alt_originorstream" id="http2_serverhttp2session_altsvc_alt_originorstream">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><code>alt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A description of the alternative service configuration as defined by <a href="https://tools.ietf.org/html/rfc7838">RFC 7838</a>.</li> <li><code>originOrStream</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Either a URL string specifying the origin (or an <code>Object</code> with an <code>origin</code> property) or the numeric identifier of an active <code>Http2Stream</code> as given by the <code>http2stream.id</code> property.</li> </ul> <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> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer(); server.on('session', (session) => { // Set altsvc for origin https://example.org:80 session.altsvc('h2=":8000"', 'https://example.org:80'); }); server.on('stream', (stream) => { // Set altsvc for a specific stream stream.session.altsvc('h2=":8000"', stream.id); }); </code></pre> <p>Sending an <code>ALTSVC</code> frame with a specific stream ID indicates that the alternate service is associated with the origin of the given <code>Http2Stream</code>.</p> <p>The <code>alt</code> and origin string <em>must</em> contain only ASCII bytes and are strictly interpreted as a sequence of ASCII bytes. The special value <code>'clear'</code> may be passed to clear any previously set alternative service for a given domain.</p> <p>When a string is passed for the <code>originOrStream</code> argument, it will be parsed as a URL and the origin will be derived. For instance, the origin for the HTTP URL <code>'https://example.org/foo/bar'</code> is the ASCII string <code>'https://example.org'</code>. An error will be thrown if either the given string cannot be parsed as a URL or if a valid origin cannot be derived.</p> <p>A <code>URL</code> object, or any object with an <code>origin</code> property, may be passed as <code>originOrStream</code>, in which case the value of the <code>origin</code> property will be used. The value of the <code>origin</code> property <em>must</em> be a properly serialized ASCII origin.</p> <h4>Specifying alternative services<span><a class="mark" href="#http2_specifying_alternative_services" id="http2_specifying_alternative_services">#</a></span></h4> <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 ASCII string containing a comma-delimited list of "alternative" protocols associated with a specific host and port.</p> <p>For example, the value <code>'h2="example.org:81"'</code> indicates that the HTTP/2 protocol is available on the host <code>'example.org'</code> on TCP/IP port 81. The host and port <em>must</em> be contained within the quote (<code>"</code>) characters.</p> <p>Multiple alternatives may be specified, for instance: <code>'h2="example.org:81", h2=":82"'</code>.</p> <p>The protocol identifier (<code>'h2'</code> in the examples) may be any valid <a href="https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids">ALPN Protocol ID</a>.</p> <p>The syntax of these values is not validated by the Node.js implementation and are passed through as provided by the user or received from the peer.</p> <h4>serverhttp2session.origin(...origins)<span><a class="mark" href="#http2_serverhttp2session_origin_origins" id="http2_serverhttp2session_origin_origins">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.12.0</span> </div> <ul> <li><code>origins</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> One or more URL Strings passed as separate arguments.</li> </ul> <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 to advertise the set of origins for which the server is capable of providing authoritative responses.</p> <pre><code class="language-js">const http2 = require('http2'); const options = getSecureOptionsSomehow(); const server = http2.createSecureServer(options); server.on('stream', (stream) => { stream.respond(); stream.end('ok'); }); server.on('session', (session) => { session.origin('https://example.com', 'https://example.org'); }); </code></pre> <p>When a string is passed as an <code>origin</code>, it will be parsed as a URL and the origin will be derived. For instance, the origin for the HTTP URL <code>'https://example.org/foo/bar'</code> is the ASCII string <code>'https://example.org'</code>. An error will be thrown if either the given string cannot be parsed as a URL or if a valid origin cannot be derived.</p> <p>A <code>URL</code> object, or any object with an <code>origin</code> property, may be passed as an <code>origin</code>, in which case the value of the <code>origin</code> property will be used. The value of the <code>origin</code> property <em>must</em> be a properly serialized ASCII origin.</p> <p>Alternatively, the <code>origins</code> option may be used when creating a new HTTP/2 server using the <code>http2.createSecureServer()</code> method:</p> <pre><code class="language-js">const http2 = require('http2'); const options = getSecureOptionsSomehow(); options.origins = ['https://example.com', 'https://example.org']; const server = http2.createSecureServer(options); server.on('stream', (stream) => { stream.respond(); stream.end('ok'); }); </code></pre> <h3>Class: ClientHttp2Session<span><a class="mark" href="#http2_class_clienthttp2session" id="http2_class_clienthttp2session">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <h4>Event: 'altsvc'<span><a class="mark" href="#http2_event_altsvc" id="http2_event_altsvc">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><code>alt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>origin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>streamId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The <code>'altsvc'</code> event is emitted whenever an <code>ALTSVC</code> frame is received by the client. The event is emitted with the <code>ALTSVC</code> value, origin, and stream ID. If no <code>origin</code> is provided in the <code>ALTSVC</code> frame, <code>origin</code> will be an empty string.</p> <pre><code class="language-js">const http2 = require('http2'); const client = http2.connect('https://example.org'); client.on('altsvc', (alt, origin, streamId) => { console.log(alt); console.log(origin); console.log(streamId); }); </code></pre> <h4>Event: 'origin'<span><a class="mark" href="#http2_event_origin" id="http2_event_origin">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.12.0</span> </div> <ul> <li><code>origins</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>The <code>'origin'</code> event is emitted whenever an <code>ORIGIN</code> frame is received by the client. The event is emitted with an array of <code>origin</code> strings. The <code>http2session.originSet</code> will be updated to include the received origins.</p> <pre><code class="language-js">const http2 = require('http2'); const client = http2.connect('https://example.org'); client.on('origin', (origins) => { for (let n = 0; n < origins.length; n++) console.log(origins[n]); }); </code></pre> <p>The <code>'origin'</code> event is only emitted when using a secure TLS connection.</p> <h4>clienthttp2session.request(headers[, options])<span><a class="mark" href="#http2_clienthttp2session_request_headers_options" id="http2_clienthttp2session_request_headers_options">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li> <p><code>headers</code> <a href="http2.html#http2_headers_object" class="type"><HTTP/2 Headers Object></a></p> </li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>endStream</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the <code>Http2Stream</code> <em>writable</em> side should be closed initially, such as when sending a <code>GET</code> request that should not expect a payload body.</li> <li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code> and <code>parent</code> 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. <strong>Default:</strong> <code>false</code>.</li> <li><code>parent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the numeric identifier of a stream the newly created stream is dependent on.</li> <li><code>weight</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the relative dependency of a stream in relation to other streams with the same <code>parent</code>. The value is a number between <code>1</code> and <code>256</code> (inclusive).</li> <li><code>waitForTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>Http2Stream</code> will emit the <code>'wantTrailers'</code> event after the final <code>DATA</code> frame has been sent.</li> </ul> </li> <li> <p>Returns: <a href="http2.html#http2_class_clienthttp2stream" class="type"><ClientHttp2Stream></a></p> </li> </ul> <p>For HTTP/2 Client <code>Http2Session</code> instances only, the <code>http2session.request()</code> creates and returns an <code>Http2Stream</code> instance that can be used to send an HTTP/2 request to the connected server.</p> <p>This method is only available if <code>http2session.type</code> is equal to <code>http2.constants.NGHTTP2_SESSION_CLIENT</code>.</p> <pre><code class="language-js">const http2 = require('http2'); const clientSession = http2.connect('https://localhost:1234'); const { HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS } = http2.constants; const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); req.on('response', (headers) => { console.log(headers[HTTP2_HEADER_STATUS]); req.on('data', (chunk) => { /* .. */ }); req.on('end', () => { /* .. */ }); }); </code></pre> <p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event is emitted immediately after queuing the last chunk of payload data to be sent. The <code>http2stream.sendTrailers()</code> method can then be called to send trailing headers to the peer.</p> <p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically close when the final <code>DATA</code> frame is transmitted. User code must call either <code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the <code>Http2Stream</code>.</p> <p>The <code>:method</code> and <code>:path</code> pseudo-headers are not specified within <code>headers</code>, they respectively default to:</p> <ul> <li><code>:method</code> = <code>'GET'</code></li> <li><code>:path</code> = <code>/</code></li> </ul> <h3>Class: Http2Stream<span><a class="mark" href="#http2_class_http2stream" id="http2_class_http2stream">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li>Extends: <a href="stream.html#stream_class_stream_duplex" class="type"><stream.Duplex></a></li> </ul> <p>Each instance of the <code>Http2Stream</code> class represents a bidirectional HTTP/2 communications stream over an <code>Http2Session</code> instance. Any single <code>Http2Session</code> may have up to 2<sup>31</sup>-1 <code>Http2Stream</code> instances over its lifetime.</p> <p>User code will not construct <code>Http2Stream</code> instances directly. Rather, these are created, managed, and provided to user code through the <code>Http2Session</code> instance. On the server, <code>Http2Stream</code> instances are created either in response to an incoming HTTP request (and handed off to user code via the <code>'stream'</code> event), or in response to a call to the <code>http2stream.pushStream()</code> method. On the client, <code>Http2Stream</code> instances are created and returned when either the <code>http2session.request()</code> method is called, or in response to an incoming <code>'push'</code> event.</p> <p>The <code>Http2Stream</code> class is a base for the <a href="#http2_class_serverhttp2stream"><code>ServerHttp2Stream</code></a> and <a href="#http2_class_clienthttp2stream"><code>ClientHttp2Stream</code></a> classes, each of which is used specifically by either the Server or Client side, respectively.</p> <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 <code>Duplex</code> is used to send data to the connected peer, while the <code>Readable</code> side is used to receive data sent by the connected peer.</p> <h4>Http2Stream Lifecycle<span><a class="mark" href="#http2_http2stream_lifecycle" id="http2_http2stream_lifecycle">#</a></span></h4> <h5>Creation<span><a class="mark" href="#http2_creation" id="http2_creation">#</a></span></h5> <p>On the server side, instances of <a href="#http2_class_serverhttp2stream"><code>ServerHttp2Stream</code></a> are created either when:</p> <ul> <li>A new HTTP/2 <code>HEADERS</code> frame with a previously unused stream ID is received;</li> <li>The <code>http2stream.pushStream()</code> method is called.</li> </ul> <p>On the client side, instances of <a href="#http2_class_clienthttp2stream"><code>ClientHttp2Stream</code></a> are created when the <code>http2session.request()</code> method is called.</p> <p>On the client, the <code>Http2Stream</code> instance returned by <code>http2session.request()</code> may not be immediately ready for use if the parent <code>Http2Session</code> has not yet been fully established. In such cases, operations called on the <code>Http2Stream</code> will be buffered until the <code>'ready'</code> event is emitted. User code should rarely, if ever, need to handle the <code>'ready'</code> event directly. The ready status of an <code>Http2Stream</code> can be determined by checking the value of <code>http2stream.id</code>. If the value is <code>undefined</code>, the stream is not yet ready for use.</p> <h5>Destruction<span><a class="mark" href="#http2_destruction" id="http2_destruction">#</a></span></h5> <p>All <a href="#http2_class_http2stream"><code>Http2Stream</code></a> instances are destroyed either when:</p> <ul> <li>An <code>RST_STREAM</code> frame for the stream is received by the connected peer, and (for client streams only) pending data has been read.</li> <li>The <code>http2stream.close()</code> method is called, and (for client streams only) pending data has been read.</li> <li>The <code>http2stream.destroy()</code> or <code>http2session.destroy()</code> methods are called.</li> </ul> <p>When an <code>Http2Stream</code> instance is destroyed, an attempt will be made to send an <code>RST_STREAM</code> frame will be sent to the connected peer.</p> <p>When the <code>Http2Stream</code> instance is destroyed, the <code>'close'</code> event will be emitted. Because <code>Http2Stream</code> is an instance of <code>stream.Duplex</code>, the <code>'end'</code> event will also be emitted if the stream data is currently flowing. The <code>'error'</code> event may also be emitted if <code>http2stream.destroy()</code> was called with an <code>Error</code> passed as the first argument.</p> <p>After the <code>Http2Stream</code> has been destroyed, the <code>http2stream.destroyed</code> property will be <code>true</code> and the <code>http2stream.rstCode</code> property will specify the <code>RST_STREAM</code> error code. The <code>Http2Stream</code> instance is no longer usable once destroyed.</p> <h4>Event: 'aborted'<span><a class="mark" href="#http2_event_aborted" id="http2_event_aborted">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'aborted'</code> event is emitted whenever a <code>Http2Stream</code> instance is abnormally aborted in mid-communication.</p> <p>The <code>'aborted'</code> event will only be emitted if the <code>Http2Stream</code> writable side has not been ended.</p> <h4>Event: 'close'<span><a class="mark" href="#http2_event_close_1" id="http2_event_close_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'close'</code> event is emitted when the <code>Http2Stream</code> is destroyed. Once this event is emitted, the <code>Http2Stream</code> instance is no longer usable.</p> <p>The HTTP/2 error code used when closing the stream can be retrieved using the <code>http2stream.rstCode</code> property. If the code is any value other than <code>NGHTTP2_NO_ERROR</code> (<code>0</code>), an <code>'error'</code> event will have also been emitted.</p> <h4>Event: 'error'<span><a class="mark" href="#http2_event_error_1" id="http2_event_error_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>The <code>'error'</code> event is emitted when an error occurs during the processing of an <code>Http2Stream</code>.</p> <h4>Event: 'frameError'<span><a class="mark" href="#http2_event_frameerror_1" id="http2_event_frameerror_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'frameError'</code> event is emitted when an error occurs while attempting to send a frame. When invoked, the handler function will receive an integer argument identifying the frame type, and an integer argument identifying the error code. The <code>Http2Stream</code> instance will be destroyed immediately after the <code>'frameError'</code> event is emitted.</p> <h4>Event: 'timeout'<span><a class="mark" href="#http2_event_timeout_1" id="http2_event_timeout_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'timeout'</code> event is emitted after no activity is received for this <code>Http2Stream</code> within the number of milliseconds set using <code>http2stream.setTimeout()</code>.</p> <h4>Event: 'trailers'<span><a class="mark" href="#http2_event_trailers" id="http2_event_trailers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'trailers'</code> event is emitted when a block of headers associated with trailing header fields is received. The listener callback is passed the <a href="#http2_headers_object">HTTP/2 Headers Object</a> and flags associated with the headers.</p> <p>Note that this event might not be emitted if <code>http2stream.end()</code> is called before trailers are received and the incoming data is not being read or listened for.</p> <pre><code class="language-js">stream.on('trailers', (headers, flags) => { console.log(headers); }); </code></pre> <h4>Event: 'wantTrailers'<span><a class="mark" href="#http2_event_wanttrailers" id="http2_event_wanttrailers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <p>The <code>'wantTrailers'</code> event is emitted when the <code>Http2Stream</code> has queued the final <code>DATA</code> frame to be sent on a frame and the <code>Http2Stream</code> is ready to send trailing headers. When initiating a request or response, the <code>waitForTrailers</code> option must be set for this event to be emitted.</p> <h4>http2stream.aborted<span><a class="mark" href="#http2_http2stream_aborted" id="http2_http2stream_aborted">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Set to <code>true</code> if the <code>Http2Stream</code> instance was aborted abnormally. When set, the <code>'aborted'</code> event will have been emitted.</p> <h4>http2stream.bufferSize<span><a class="mark" href="#http2_http2stream_buffersize" id="http2_http2stream_buffersize">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.16.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>This property shows the number of characters currently buffered to be written. See <a href="net.html#net_socket_buffersize"><code>net.Socket.bufferSize</code></a> for details.</p> <h4>http2stream.close(code[, callback])<span><a class="mark" href="#http2_http2stream_close_code_callback" id="http2_http2stream_close_code_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Unsigned 32-bit integer identifying the error code. <strong>Default:</strong> <code>http2.constants.NGHTTP2_NO_ERROR</code> (<code>0x00</code>).</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> An optional function registered to listen for the <code>'close'</code> event.</li> </ul> <p>Closes the <code>Http2Stream</code> instance by sending an <code>RST_STREAM</code> frame to the connected HTTP/2 peer.</p> <h4>http2stream.closed<span><a class="mark" href="#http2_http2stream_closed" id="http2_http2stream_closed">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Set to <code>true</code> if the <code>Http2Stream</code> instance has been closed.</p> <h4>http2stream.destroyed<span><a class="mark" href="#http2_http2stream_destroyed" id="http2_http2stream_destroyed">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Set to <code>true</code> if the <code>Http2Stream</code> instance has been destroyed and is no longer usable.</p> <h4>http2stream.endAfterHeaders<span><a class="mark" href="#http2_http2stream_endafterheaders" id="http2_http2stream_endafterheaders">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.11.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Set the <code>true</code> if the <code>END_STREAM</code> flag was set in the request or response HEADERS frame received, indicating that no additional data should be received and the readable side of the <code>Http2Stream</code> will be closed.</p> <h4>http2stream.pending<span><a class="mark" href="#http2_http2stream_pending" id="http2_http2stream_pending">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Set to <code>true</code> if the <code>Http2Stream</code> instance has not yet been assigned a numeric stream identifier.</p> <h4>http2stream.priority(options)<span><a class="mark" href="#http2_http2stream_priority_options" id="http2_http2stream_priority_options">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code> and <code>parent</code> 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. <strong>Default:</strong> <code>false</code>.</li> <li><code>parent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the numeric identifier of a stream this stream is dependent on.</li> <li><code>weight</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the relative dependency of a stream in relation to other streams with the same <code>parent</code>. The value is a number between <code>1</code> and <code>256</code> (inclusive).</li> <li><code>silent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, changes the priority locally without sending a <code>PRIORITY</code> frame to the connected peer.</li> </ul> </li> </ul> <p>Updates the priority for this <code>Http2Stream</code> instance.</p> <h4>http2stream.rstCode<span><a class="mark" href="#http2_http2stream_rstcode" id="http2_http2stream_rstcode">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Set to the <code>RST_STREAM</code> <a href="#error_codes">error code</a> reported when the <code>Http2Stream</code> is destroyed after either receiving an <code>RST_STREAM</code> frame from the connected peer, calling <code>http2stream.close()</code>, or <code>http2stream.destroy()</code>. Will be <code>undefined</code> if the <code>Http2Stream</code> has not been closed.</p> <h4>http2stream.sentHeaders<span><a class="mark" href="#http2_http2stream_sentheaders" id="http2_http2stream_sentheaders">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.5.0</span> </div> <ul> <li><a href="http2.html#http2_headers_object" class="type"><HTTP/2 Headers Object></a></li> </ul> <p>An object containing the outbound headers sent for this <code>Http2Stream</code>.</p> <h4>http2stream.sentInfoHeaders<span><a class="mark" href="#http2_http2stream_sentinfoheaders" id="http2_http2stream_sentinfoheaders">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.5.0</span> </div> <ul> <li><a href="http2.html#http2_headers_object" class="type"><HTTP/2 Headers Object[]></a></li> </ul> <p>An array of objects containing the outbound informational (additional) headers sent for this <code>Http2Stream</code>.</p> <h4>http2stream.sentTrailers<span><a class="mark" href="#http2_http2stream_senttrailers" id="http2_http2stream_senttrailers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.5.0</span> </div> <ul> <li><a href="http2.html#http2_headers_object" class="type"><HTTP/2 Headers Object></a></li> </ul> <p>An object containing the outbound trailers sent for this <code>HttpStream</code>.</p> <h4>http2stream.session<span><a class="mark" href="#http2_http2stream_session" id="http2_http2stream_session">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="http2.html#http2_class_http2session" class="type"><Http2Session></a></li> </ul> <p>A reference to the <code>Http2Session</code> instance that owns this <code>Http2Stream</code>. The value will be <code>undefined</code> after the <code>Http2Stream</code> instance is destroyed.</p> <h4>http2stream.setTimeout(msecs, callback)<span><a class="mark" href="#http2_http2stream_settimeout_msecs_callback" id="http2_http2stream_settimeout_msecs_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <pre><code class="language-js">const http2 = require('http2'); const client = http2.connect('http://example.org:8000'); const { NGHTTP2_CANCEL } = http2.constants; const req = client.request({ ':path': '/' }); // Cancel the stream if there's no activity after 5 seconds req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); </code></pre> <h4>http2stream.state<span><a class="mark" href="#http2_http2stream_state" id="http2_http2stream_state">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>Provides miscellaneous information about the current state of the <code>Http2Stream</code>.</p> <ul> <li> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <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 for this <code>Http2Stream</code> without receiving a <code>WINDOW_UPDATE</code>.</li> <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 <code>Http2Stream</code> as determined by <code>nghttp2</code>.</li> <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> <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 remotely.</li> <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> instances that depend on this <code>Http2Stream</code> as specified using <code>PRIORITY</code> frames.</li> <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> </ul> </li> </ul> <p>A current state of this <code>Http2Stream</code>.</p> <h4>http2stream.sendTrailers(headers)<span><a class="mark" href="#http2_http2stream_sendtrailers_headers" id="http2_http2stream_sendtrailers_headers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>headers</code> <a href="http2.html#http2_headers_object" class="type"><HTTP/2 Headers Object></a></li> </ul> <p>Sends a trailing <code>HEADERS</code> frame to the connected HTTP/2 peer. This method will cause the <code>Http2Stream</code> to be immediately closed and must only be called after the <code>'wantTrailers'</code> event has been emitted. When sending a request or sending a response, the <code>options.waitForTrailers</code> option must be set in order to keep the <code>Http2Stream</code> open after the final <code>DATA</code> frame so that trailers can be sent.</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { stream.respond(undefined, { waitForTrailers: true }); stream.on('wantTrailers', () => { stream.sendTrailers({ xyz: 'abc' }); }); stream.end('Hello World'); }); </code></pre> <p>The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header fields (e.g. <code>':method'</code>, <code>':path'</code>, etc).</p> <h3>Class: ClientHttp2Stream<span><a class="mark" href="#http2_class_clienthttp2stream" id="http2_class_clienthttp2stream">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li>Extends <a href="http2.html#http2_class_http2stream" class="type"><Http2Stream></a></li> </ul> <p>The <code>ClientHttp2Stream</code> class is an extension of <code>Http2Stream</code> that is used exclusively on HTTP/2 Clients. <code>Http2Stream</code> instances on the client provide events such as <code>'response'</code> and <code>'push'</code> that are only relevant on the client.</p> <h4>Event: 'continue'<span><a class="mark" href="#http2_event_continue" id="http2_event_continue">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <p>Emitted when the server sends a <code>100 Continue</code> status, usually because the request contained <code>Expect: 100-continue</code>. This is an instruction that the client should send the request body.</p> <h4>Event: 'headers'<span><a class="mark" href="#http2_event_headers" id="http2_event_headers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'headers'</code> event is emitted when an additional block of headers is received for a stream, such as when a block of <code>1xx</code> informational headers is received. The listener callback is passed the <a href="#http2_headers_object">HTTP/2 Headers Object</a> and flags associated with the headers.</p> <pre><code class="language-js">stream.on('headers', (headers, flags) => { console.log(headers); }); </code></pre> <h4>Event: 'push'<span><a class="mark" href="#http2_event_push" id="http2_event_push">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'push'</code> event is emitted when response headers for a Server Push stream are received. The listener callback is passed the <a href="#http2_headers_object">HTTP/2 Headers Object</a> and flags associated with the headers.</p> <pre><code class="language-js">stream.on('push', (headers, flags) => { console.log(headers); }); </code></pre> <h4>Event: 'response'<span><a class="mark" href="#http2_event_response" id="http2_event_response">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'response'</code> event is emitted when a response <code>HEADERS</code> frame has been received for this stream from the connected HTTP/2 server. The listener is invoked with two arguments: an <code>Object</code> containing the received <a href="#http2_headers_object">HTTP/2 Headers Object</a>, and flags associated with the headers.</p> <pre><code class="language-js">const http2 = require('http2'); const client = http2.connect('https://localhost'); const req = client.request({ ':path': '/' }); req.on('response', (headers, flags) => { console.log(headers[':status']); }); </code></pre> <h3>Class: ServerHttp2Stream<span><a class="mark" href="#http2_class_serverhttp2stream" id="http2_class_serverhttp2stream">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li>Extends: <a href="http2.html#http2_class_http2stream" class="type"><Http2Stream></a></li> </ul> <p>The <code>ServerHttp2Stream</code> class is an extension of <a href="#http2_class_http2stream"><code>Http2Stream</code></a> that is used exclusively on HTTP/2 Servers. <code>Http2Stream</code> instances on the server provide additional methods such as <code>http2stream.pushStream()</code> and <code>http2stream.respond()</code> that are only relevant on the server.</p> <h4>http2stream.additionalHeaders(headers)<span><a class="mark" href="#http2_http2stream_additionalheaders_headers" id="http2_http2stream_additionalheaders_headers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>headers</code> <a href="http2.html#http2_headers_object" class="type"><HTTP/2 Headers Object></a></li> </ul> <p>Sends an additional informational <code>HEADERS</code> frame to the connected HTTP/2 peer.</p> <h4>http2stream.headersSent<span><a class="mark" href="#http2_http2stream_headerssent" id="http2_http2stream_headerssent">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>True if headers were sent, false otherwise (read-only).</p> <h4>http2stream.pushAllowed<span><a class="mark" href="#http2_http2stream_pushallowed" id="http2_http2stream_pushallowed">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Read-only property mapped to the <code>SETTINGS_ENABLE_PUSH</code> flag of the remote client's most recent <code>SETTINGS</code> frame. Will be <code>true</code> if the remote peer accepts push streams, <code>false</code> otherwise. Settings are the same for every <code>Http2Stream</code> in the same <code>Http2Session</code>.</p> <h4>http2stream.pushStream(headers[, options], callback)<span><a class="mark" href="#http2_http2stream_pushstream_headers_options_callback" id="http2_http2stream_pushstream_headers_options_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>headers</code> <a href="http2.html#http2_headers_object" class="type"><HTTP/2 Headers Object></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code> and <code>parent</code> 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. <strong>Default:</strong> <code>false</code>.</li> <li><code>parent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the numeric identifier of a stream the newly created stream is dependent on.</li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Callback that is called once the push stream has been initiated.</p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>pushStream</code> <a href="http2.html#http2_class_serverhttp2stream" class="type"><ServerHttp2Stream></a> The returned <code>pushStream</code> object.</li> <li><code>headers</code> <a href="http2.html#http2_headers_object" class="type"><HTTP/2 Headers Object></a> Headers object the <code>pushStream</code> was initiated with.</li> </ul> </li> </ul> <p>Initiates a push stream. The callback is invoked with the new <code>Http2Stream</code> instance created for the push stream passed as the second argument, or an <code>Error</code> passed as the first argument.</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { stream.respond({ ':status': 200 }); stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { if (err) throw err; pushStream.respond({ ':status': 200 }); pushStream.end('some pushed data'); }); stream.end('some data'); }); </code></pre> <p>Setting the weight of a push stream is not allowed in the <code>HEADERS</code> frame. Pass a <code>weight</code> value to <code>http2stream.priority</code> with the <code>silent</code> option set to <code>true</code> to enable server-side bandwidth balancing between concurrent streams.</p> <p>Calling <code>http2stream.pushStream()</code> from within a pushed stream is not permitted and will throw an error.</p> <h4>http2stream.respond([headers[, options]])<span><a class="mark" href="#http2_http2stream_respond_headers_options" id="http2_http2stream_respond_headers_options">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>headers</code> <a href="http2.html#http2_headers_object" class="type"><HTTP/2 Headers Object></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>endStream</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Set to <code>true</code> to indicate that the response will not include payload data.</li> <li><code>waitForTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>Http2Stream</code> will emit the <code>'wantTrailers'</code> event after the final <code>DATA</code> frame has been sent.</li> </ul> </li> </ul> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { stream.respond({ ':status': 200 }); stream.end('some data'); }); </code></pre> <p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event will be emitted immediately after queuing the last chunk of payload data to be sent. The <code>http2stream.sendTrailers()</code> method can then be used to sent trailing header fields to the peer.</p> <p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically close when the final <code>DATA</code> frame is transmitted. User code must call either <code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the <code>Http2Stream</code>.</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { stream.respond({ ':status': 200 }, { waitForTrailers: true }); stream.on('wantTrailers', () => { stream.sendTrailers({ ABC: 'some value to send' }); }); stream.end('some data'); }); </code></pre> <h4>http2stream.respondWithFD(fd[, headers[, options]])<span><a class="mark" href="#http2_http2stream_respondwithfd_fd_headers_options" id="http2_http2stream_respondwithfd_fd_headers_options">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Any readable file descriptor, not necessarily for a regular file, is supported now.</p></td></tr> <tr><td>v8.4.0</td> <td><p><span>Added in: v8.4.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A readable file descriptor.</li> <li><code>headers</code> <a href="http2.html#http2_headers_object" class="type"><HTTP/2 Headers Object></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>statCheck</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li><code>waitForTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>Http2Stream</code> will emit the <code>'wantTrailers'</code> event after the final <code>DATA</code> frame has been sent.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The offset position at which to begin reading.</li> <li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The amount of data from the fd to send.</li> </ul> </li> </ul> <p>Initiates a response whose data is read from the given file descriptor. No validation is performed on the given file descriptor. If an error occurs while attempting to read data using the file descriptor, the <code>Http2Stream</code> will be closed using an <code>RST_STREAM</code> frame using the standard <code>INTERNAL_ERROR</code> code.</p> <p>When used, the <code>Http2Stream</code> object's <code>Duplex</code> interface will be closed automatically.</p> <pre><code class="language-js">const http2 = require('http2'); const fs = require('fs'); const server = http2.createServer(); server.on('stream', (stream) => { const fd = fs.openSync('/some/file', 'r'); const stat = fs.fstatSync(fd); const headers = { 'content-length': stat.size, 'last-modified': stat.mtime.toUTCString(), 'content-type': 'text/plain' }; stream.respondWithFD(fd, headers); stream.on('close', () => fs.closeSync(fd)); }); </code></pre> <p>The optional <code>options.statCheck</code> function may be specified to give user code an opportunity to set additional content headers based on the <code>fs.Stat</code> details of the given fd. If the <code>statCheck</code> function is provided, the <code>http2stream.respondWithFD()</code> method will perform an <code>fs.fstat()</code> call to collect details on the provided file descriptor.</p> <p>The <code>offset</code> and <code>length</code> options may be used to limit the response to a specific range subset. This can be used, for instance, to support HTTP Range requests.</p> <p>The file descriptor is not closed when the stream is closed, so it will need to be closed manually once it is no longer needed. Note that using the same file descriptor concurrently for multiple streams is not supported and may result in data loss. Re-using a file descriptor after a stream has finished is supported.</p> <p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event will be emitted immediately after queuing the last chunk of payload data to be sent. The <code>http2stream.sendTrailers()</code> method can then be used to sent trailing header fields to the peer.</p> <p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically close when the final <code>DATA</code> frame is transmitted. User code <em>must</em> call either <code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the <code>Http2Stream</code>.</p> <pre><code class="language-js">const http2 = require('http2'); const fs = require('fs'); const server = http2.createServer(); server.on('stream', (stream) => { const fd = fs.openSync('/some/file', 'r'); const stat = fs.fstatSync(fd); const headers = { 'content-length': stat.size, 'last-modified': stat.mtime.toUTCString(), 'content-type': 'text/plain' }; stream.respondWithFD(fd, headers, { waitForTrailers: true }); stream.on('wantTrailers', () => { stream.sendTrailers({ ABC: 'some value to send' }); }); stream.on('close', () => fs.closeSync(fd)); }); </code></pre> <h4>http2stream.respondWithFile(path[, headers[, options]])<span><a class="mark" href="#http2_http2stream_respondwithfile_path_headers_options" id="http2_http2stream_respondwithfile_path_headers_options">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Any readable file, not necessarily a regular file, is supported now.</p></td></tr> <tr><td>v8.4.0</td> <td><p><span>Added in: v8.4.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>headers</code> <a href="http2.html#http2_headers_object" class="type"><HTTP/2 Headers Object></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>statCheck</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li><code>onError</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Callback function invoked in the case of an error before send.</li> <li><code>waitForTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>Http2Stream</code> will emit the <code>'wantTrailers'</code> event after the final <code>DATA</code> frame has been sent.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The offset position at which to begin reading.</li> <li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The amount of data from the fd to send.</li> </ul> </li> </ul> <p>Sends a regular file as the response. The <code>path</code> must specify a regular file or an <code>'error'</code> event will be emitted on the <code>Http2Stream</code> object.</p> <p>When used, the <code>Http2Stream</code> object's <code>Duplex</code> interface will be closed automatically.</p> <p>The optional <code>options.statCheck</code> function may be specified to give user code an opportunity to set additional content headers based on the <code>fs.Stat</code> details of the given file:</p> <p>If an error occurs while attempting to read the file data, the <code>Http2Stream</code> will be closed using an <code>RST_STREAM</code> frame using the standard <code>INTERNAL_ERROR</code> code. If the <code>onError</code> callback is defined, then it will be called. Otherwise the stream will be destroyed.</p> <p>Example using a file path:</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { function statCheck(stat, headers) { headers['last-modified'] = stat.mtime.toUTCString(); } function onError(err) { if (err.code === 'ENOENT') { stream.respond({ ':status': 404 }); } else { stream.respond({ ':status': 500 }); } stream.end(); } stream.respondWithFile('/some/file', { 'content-type': 'text/plain' }, { statCheck, onError }); }); </code></pre> <p>The <code>options.statCheck</code> function may also be used to cancel the send operation by returning <code>false</code>. For instance, a conditional request may check the stat results to determine if the file has been modified to return an appropriate <code>304</code> response:</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { function statCheck(stat, headers) { // Check the stat here... stream.respond({ ':status': 304 }); return false; // Cancel the send operation } stream.respondWithFile('/some/file', { 'content-type': 'text/plain' }, { statCheck }); }); </code></pre> <p>The <code>content-length</code> header field will be automatically set.</p> <p>The <code>offset</code> and <code>length</code> options may be used to limit the response to a specific range subset. This can be used, for instance, to support HTTP Range requests.</p> <p>The <code>options.onError</code> function may also be used to handle all the errors that could happen before the delivery of the file is initiated. The default behavior is to destroy the stream.</p> <p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event will be emitted immediately after queuing the last chunk of payload data to be sent. The <code>http2stream.sendTrailers()</code> method can then be used to sent trailing header fields to the peer.</p> <p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically close when the final <code>DATA</code> frame is transmitted. User code must call either <code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the <code>Http2Stream</code>.</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { stream.respondWithFile('/some/file', { 'content-type': 'text/plain' }, { waitForTrailers: true }); stream.on('wantTrailers', () => { stream.sendTrailers({ ABC: 'some value to send' }); }); }); </code></pre> <h3>Class: Http2Server<span><a class="mark" href="#http2_class_http2server" id="http2_class_http2server">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li>Extends: <a href="net.html#net_class_net_server" class="type"><net.Server></a></li> </ul> <p>Instances of <code>Http2Server</code> are created using the <code>http2.createServer()</code> function. The <code>Http2Server</code> class is not exported directly by the <code>http2</code> module.</p> <h4>Event: 'checkContinue'<span><a class="mark" href="#http2_event_checkcontinue" id="http2_event_checkcontinue">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><code>request</code> <a href="http2.html#http2_class_http2_http2serverrequest" class="type"><http2.Http2ServerRequest></a></li> <li><code>response</code> <a href="http2.html#http2_class_http2_http2serverresponse" class="type"><http2.Http2ServerResponse></a></li> </ul> <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 supplied a callback function, the <code>'checkContinue'</code> event is emitted each time a request with an HTTP <code>Expect: 100-continue</code> is received. If this event is not listened for, the server will automatically respond with a status <code>100 Continue</code> as appropriate.</p> <p>Handling this event involves calling <a href="#http2_response_writecontinue"><code>response.writeContinue()</code></a> if the client should continue to send the request body, or generating an appropriate HTTP response (e.g. 400 Bad Request) if the client should not continue to send the request body.</p> <p>Note that when this event is emitted and handled, the <a href="#http2_event_request"><code>'request'</code></a> event will not be emitted.</p> <h4>Event: 'request'<span><a class="mark" href="#http2_event_request" id="http2_event_request">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>request</code> <a href="http2.html#http2_class_http2_http2serverrequest" class="type"><http2.Http2ServerRequest></a></li> <li><code>response</code> <a href="http2.html#http2_class_http2_http2serverresponse" class="type"><http2.Http2ServerResponse></a></li> </ul> <p>Emitted each time there is a request. Note that there may be multiple requests per session. See the <a href="#http2_compatibility_api">Compatibility API</a>.</p> <h4>Event: 'session'<span><a class="mark" href="#http2_event_session" id="http2_event_session">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'session'</code> event is emitted when a new <code>Http2Session</code> is created by the <code>Http2Server</code>.</p> <h4>Event: 'sessionError'<span><a class="mark" href="#http2_event_sessionerror" id="http2_event_sessionerror">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'sessionError'</code> event is emitted when an <code>'error'</code> event is emitted by an <code>Http2Session</code> object associated with the <code>Http2Server</code>.</p> <h4>Event: 'stream'<span><a class="mark" href="#http2_event_stream_1" id="http2_event_stream_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'stream'</code> event is emitted when a <code>'stream'</code> event has been emitted by an <code>Http2Session</code> associated with the server.</p> <pre><code class="language-js">const http2 = require('http2'); const { HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS, HTTP2_HEADER_CONTENT_TYPE } = http2.constants; const server = http2.createServer(); server.on('stream', (stream, headers, flags) => { const method = headers[HTTP2_HEADER_METHOD]; const path = headers[HTTP2_HEADER_PATH]; // ... stream.respond({ [HTTP2_HEADER_STATUS]: 200, [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain' }); stream.write('hello '); stream.end('world'); }); </code></pre> <h4>Event: 'timeout'<span><a class="mark" href="#http2_event_timeout_2" id="http2_event_timeout_2">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'timeout'</code> event is emitted when there is no activity on the Server for a given number of milliseconds set using <code>http2server.setTimeout()</code>. <strong>Default:</strong> 2 minutes.</p> <h4>server.close([callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1562">[src]</a><span><a class="mark" href="#http2_server_close_callback" id="http2_server_close_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Stops the server from accepting new connections. See <a href="net.html#net_server_close_callback"><code>net.Server.close()</code></a>.</p> <p>Note that this is not analogous to restricting new requests since HTTP/2 connections are persistent. To achieve a similar graceful shutdown behavior, consider also using <a href="#http2_http2session_close_callback"><code>http2session.close()</code></a> on active sessions.</p> <h4>server.setTimeout([msecs][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/_http_server.js#L323">[src]</a><span><a class="mark" href="#http2_server_settimeout_msecs_callback" id="http2_server_settimeout_msecs_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>120000</code> (2 minutes)</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="http2.html#http2_class_http2server" class="type"><Http2Server></a></li> </ul> <p>Used to set the timeout value for http2 server requests, and sets a callback function that is called when there is no activity on the <code>Http2Server</code> after <code>msecs</code> milliseconds.</p> <p>The given callback is registered as a listener on the <code>'timeout'</code> event.</p> <p>In case of no callback function were assigned, a new <code>ERR_INVALID_CALLBACK</code> error will be thrown.</p> <h3>Class: Http2SecureServer<span><a class="mark" href="#http2_class_http2secureserver" id="http2_class_http2secureserver">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li>Extends: <a href="tls.html#tls_class_tls_server" class="type"><tls.Server></a></li> </ul> <p>Instances of <code>Http2SecureServer</code> are created using the <code>http2.createSecureServer()</code> function. The <code>Http2SecureServer</code> class is not exported directly by the <code>http2</code> module.</p> <h4>Event: 'checkContinue'<span><a class="mark" href="#http2_event_checkcontinue_1" id="http2_event_checkcontinue_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><code>request</code> <a href="http2.html#http2_class_http2_http2serverrequest" class="type"><http2.Http2ServerRequest></a></li> <li><code>response</code> <a href="http2.html#http2_class_http2_http2serverresponse" class="type"><http2.Http2ServerResponse></a></li> </ul> <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> is supplied a callback function, the <code>'checkContinue'</code> event is emitted each time a request with an HTTP <code>Expect: 100-continue</code> is received. If this event is not listened for, the server will automatically respond with a status <code>100 Continue</code> as appropriate.</p> <p>Handling this event involves calling <a href="#http2_response_writecontinue"><code>response.writeContinue()</code></a> if the client should continue to send the request body, or generating an appropriate HTTP response (e.g. 400 Bad Request) if the client should not continue to send the request body.</p> <p>Note that when this event is emitted and handled, the <a href="#http2_event_request"><code>'request'</code></a> event will not be emitted.</p> <h4>Event: 'request'<span><a class="mark" href="#http2_event_request_1" id="http2_event_request_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>request</code> <a href="http2.html#http2_class_http2_http2serverrequest" class="type"><http2.Http2ServerRequest></a></li> <li><code>response</code> <a href="http2.html#http2_class_http2_http2serverresponse" class="type"><http2.Http2ServerResponse></a></li> </ul> <p>Emitted each time there is a request. Note that there may be multiple requests per session. See the <a href="#http2_compatibility_api">Compatibility API</a>.</p> <h4>Event: 'session'<span><a class="mark" href="#http2_event_session_1" id="http2_event_session_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'session'</code> event is emitted when a new <code>Http2Session</code> is created by the <code>Http2SecureServer</code>.</p> <h4>Event: 'sessionError'<span><a class="mark" href="#http2_event_sessionerror_1" id="http2_event_sessionerror_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'sessionError'</code> event is emitted when an <code>'error'</code> event is emitted by an <code>Http2Session</code> object associated with the <code>Http2SecureServer</code>.</p> <h4>Event: 'stream'<span><a class="mark" href="#http2_event_stream_2" id="http2_event_stream_2">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'stream'</code> event is emitted when a <code>'stream'</code> event has been emitted by an <code>Http2Session</code> associated with the server.</p> <pre><code class="language-js">const http2 = require('http2'); const { HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS, HTTP2_HEADER_CONTENT_TYPE } = http2.constants; const options = getOptionsSomehow(); const server = http2.createSecureServer(options); server.on('stream', (stream, headers, flags) => { const method = headers[HTTP2_HEADER_METHOD]; const path = headers[HTTP2_HEADER_PATH]; // ... stream.respond({ [HTTP2_HEADER_STATUS]: 200, [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain' }); stream.write('hello '); stream.end('world'); }); </code></pre> <h4>Event: 'timeout'<span><a class="mark" href="#http2_event_timeout_3" id="http2_event_timeout_3">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'timeout'</code> event is emitted when there is no activity on the Server for a given number of milliseconds set using <code>http2secureServer.setTimeout()</code>. <strong>Default:</strong> 2 minutes.</p> <h4>Event: 'unknownProtocol'<span><a class="mark" href="#http2_event_unknownprotocol" id="http2_event_unknownprotocol">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'unknownProtocol'</code> event is emitted when a connecting client fails to negotiate an allowed protocol (i.e. HTTP/2 or HTTP/1.1). The event handler receives the socket for handling. If no listener is registered for this event, the connection is terminated. A timeout may be specified using the <code>'unknownProtocolTimeout'</code> option passed to <a href="#http2_http2_createsecureserver_options_onrequesthandler"><code>http2.createSecureServer()</code></a>. See the <a href="#http2_compatibility_api">Compatibility API</a>.</p> <h4>server.close([callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1562">[src]</a><span><a class="mark" href="#http2_server_close_callback_1" id="http2_server_close_callback_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Stops the server from accepting new connections. See <a href="tls.html#tls_server_close_callback"><code>tls.Server.close()</code></a>.</p> <p>Note that this is not analogous to restricting new requests since HTTP/2 connections are persistent. To achieve a similar graceful shutdown behavior, consider also using <a href="#http2_http2session_close_callback"><code>http2session.close()</code></a> on active sessions.</p> <h4>server.setTimeout([msecs][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/_http_server.js#L323">[src]</a><span><a class="mark" href="#http2_server_settimeout_msecs_callback_1" id="http2_server_settimeout_msecs_callback_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>120000</code> (2 minutes)</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="http2.html#http2_class_http2secureserver" class="type"><Http2SecureServer></a></li> </ul> <p>Used to set the timeout value for http2 secure server requests, and sets a callback function that is called when there is no activity on the <code>Http2SecureServer</code> after <code>msecs</code> milliseconds.</p> <p>The given callback is registered as a listener on the <code>'timeout'</code> event.</p> <p>In case of no callback function were assigned, a new <code>ERR_INVALID_CALLBACK</code> error will be thrown.</p> <h3>http2.createServer(options[, onRequestHandler])<span><a class="mark" href="#http2_http2_createserver_options_onrequesthandler" id="http2_http2_createserver_options_onrequesthandler">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.24.0</td> <td><p>Added <code>unknownProtocolTimeout</code> option with a default of 10000.</p></td></tr> <tr><td>v10.21.0</td> <td><p>Added <code>maxSettings</code> option with a default of 32.</p></td></tr> <tr><td>v9.6.0</td> <td><p>Added the <code>Http1IncomingMessage</code> and <code>Http1ServerResponse</code> option.</p></td></tr> <tr><td>v8.9.3</td> <td><p>Added the <code>maxOutstandingPings</code> option with a default limit of 10.</p></td></tr> <tr><td>v8.9.3</td> <td><p>Added the <code>maxHeaderListPairs</code> option with a default limit of 128 header pairs.</p></td></tr> <tr><td>v8.4.0</td> <td><p><span>Added in: v8.4.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>maxDeflateDynamicTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum dynamic table size for deflating header fields. <strong>Default:</strong> <code>4Kib</code>.</li> <li><code>maxSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of settings entries per <code>SETTINGS</code> frame. The minimum value allowed is <code>1</code>. <strong>Default:</strong> <code>32</code>.</li> <li><code>maxSessionMemory</code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum memory that the <code>Http2Session</code> is permitted to use. The value is expressed in terms of number of megabytes, e.g. <code>1</code> equal 1 megabyte. The minimum value allowed is <code>1</code>. This is a credit based limit, existing <code>Http2Stream</code>s may cause this limit to be exceeded, but new <code>Http2Stream</code> instances will be rejected while this limit is exceeded. The current number of <code>Http2Stream</code> sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged <code>PING</code> and <code>SETTINGS</code> frames are all counted towards the current limit. <strong>Default:</strong> <code>10</code>.</li> <li><code>maxHeaderListPairs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of header entries. The minimum value is <code>4</code>. <strong>Default:</strong> <code>128</code>.</li> <li><code>maxOutstandingPings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of outstanding, unacknowledged pings. <strong>Default:</strong> <code>10</code>.</li> <li><code>maxSendHeaderBlockLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a <code>'frameError'</code> event being emitted and the stream being closed and destroyed.</li> <li> <p><code>paddingStrategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Identifies the strategy used for determining the amount of padding to use for <code>HEADERS</code> and <code>DATA</code> frames. <strong>Default:</strong> <code>http2.constants.PADDING_STRATEGY_NONE</code>. Value may be one of:</p> <ul> <li><code>http2.constants.PADDING_STRATEGY_NONE</code> - Specifies that no padding is to be applied.</li> <li><code>http2.constants.PADDING_STRATEGY_MAX</code> - Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied.</li> <li><code>http2.constants.PADDING_STRATEGY_CALLBACK</code> - Specifies that the user provided <code>options.selectPadding()</code> callback is to be used to determine the amount of padding.</li> <li><code>http2.constants.PADDING_STRATEGY_ALIGNED</code> - Will <em>attempt</em> 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 <em>not</em> necessarily be aligned at 8 bytes.</li> </ul> </li> <li><code>peerMaxConcurrentStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of concurrent streams for the remote peer as if a <code>SETTINGS</code> frame had been received. Will be overridden if the remote peer sets its own value for <code>maxConcurrentStreams</code>. <strong>Default:</strong> <code>100</code>.</li> <li><code>selectPadding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> When <code>options.paddingStrategy</code> is equal to <code>http2.constants.PADDING_STRATEGY_CALLBACK</code>, provides the callback function used to determine the padding. See <a href="#http2_using_options_selectpadding">Using <code>options.selectPadding()</code></a>.</li> <li><code>settings</code> <a href="http2.html#http2_settings_object" class="type"><HTTP/2 Settings Object></a> The initial settings to send to the remote peer upon connection.</li> <li><code>Http1IncomingMessage</code> <a href="http.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a> Specifies the <code>IncomingMessage</code> class to used for HTTP/1 fallback. Useful for extending the original <code>http.IncomingMessage</code>. <strong>Default:</strong> <code>http.IncomingMessage</code>.</li> <li><code>Http1ServerResponse</code> <a href="http.html#http_class_http_serverresponse" class="type"><http.ServerResponse></a> Specifies the <code>ServerResponse</code> class to used for HTTP/1 fallback. Useful for extending the original <code>http.ServerResponse</code>. <strong>Default:</strong> <code>http.ServerResponse</code>.</li> <li><code>Http2ServerRequest</code> <a href="http2.html#http2_class_http2_http2serverrequest" class="type"><http2.Http2ServerRequest></a> Specifies the <code>Http2ServerRequest</code> class to use. Useful for extending the original <code>Http2ServerRequest</code>. <strong>Default:</strong> <code>Http2ServerRequest</code>.</li> <li><code>Http2ServerResponse</code> <a href="http2.html#http2_class_http2_http2serverresponse" class="type"><http2.Http2ServerResponse></a> Specifies the <code>Http2ServerResponse</code> class to use. Useful for extending the original <code>Http2ServerResponse</code>. <strong>Default:</strong> <code>Http2ServerResponse</code>.</li> <li><code>unknownProtocolTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies a timeout in milliseconds that a server should wait when an <a href="#http2_event_unknownprotocol"><code>'unknownProtocol'</code></a> is emitted. If the socket has not been destroyed by that time the server will destroy it. <strong>Default:</strong> <code>10000</code>.</li> </ul> </li> <li><code>onRequestHandler</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> See <a href="#http2_compatibility_api">Compatibility API</a></li> <li>Returns: <a href="http2.html#http2_class_http2server" class="type"><Http2Server></a></li> </ul> <p>Returns a <code>net.Server</code> instance that creates and manages <code>Http2Session</code> instances.</p> <p>Since there are no browsers known that support <a href="https://http2.github.io/faq/#does-http2-require-encryption">unencrypted HTTP/2</a>, the use of <a href="#http2_http2_createsecureserver_options_onrequesthandler"><code>http2.createSecureServer()</code></a> is necessary when communicating with browser clients.</p> <pre><code class="language-js">const http2 = require('http2'); // Create an unencrypted HTTP/2 server. // Since there are no browsers known that support // unencrypted HTTP/2, the use of `http2.createSecureServer()` // is necessary when communicating with browser clients. const server = http2.createServer(); server.on('stream', (stream, headers) => { stream.respond({ 'content-type': 'text/html', ':status': 200 }); stream.end('<h1>Hello World</h1>'); }); server.listen(80); </code></pre> <h3>http2.createSecureServer(options[, onRequestHandler])<span><a class="mark" href="#http2_http2_createsecureserver_options_onrequesthandler" id="http2_http2_createsecureserver_options_onrequesthandler">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.24.0</td> <td><p>Added <code>unknownProtocolTimeout</code> option with a default of 10000.</p></td></tr> <tr><td>v10.21.0</td> <td><p>Added <code>maxSettings</code> option with a default of 32.</p></td></tr> <tr><td>v10.12.0</td> <td><p>Added the <code>origins</code> option to automatically send an <code>ORIGIN</code> frame on <code>Http2Session</code> startup.</p></td></tr> <tr><td>v8.9.3</td> <td><p>Added the <code>maxOutstandingPings</code> option with a default limit of 10.</p></td></tr> <tr><td>v8.9.3</td> <td><p>Added the <code>maxHeaderListPairs</code> option with a default limit of 128 header pairs.</p></td></tr> <tr><td>v8.4.0</td> <td><p><span>Added in: v8.4.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>allowHTTP1</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Incoming client connections that do not support HTTP/2 will be downgraded to HTTP/1.x when set to <code>true</code>. See the <a href="#http2_event_unknownprotocol"><code>'unknownProtocol'</code></a> event. See <a href="#http2_alpn_negotiation">ALPN negotiation</a>. <strong>Default:</strong> <code>false</code>.</li> <li><code>maxDeflateDynamicTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum dynamic table size for deflating header fields. <strong>Default:</strong> <code>4Kib</code>.</li> <li><code>maxSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of settings entries per <code>SETTINGS</code> frame. The minimum value allowed is <code>1</code>. <strong>Default:</strong> <code>32</code>.</li> <li><code>maxSessionMemory</code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum memory that the <code>Http2Session</code> is permitted to use. The value is expressed in terms of number of megabytes, e.g. <code>1</code> equal 1 megabyte. The minimum value allowed is <code>1</code>. This is a credit based limit, existing <code>Http2Stream</code>s may cause this limit to be exceeded, but new <code>Http2Stream</code> instances will be rejected while this limit is exceeded. The current number of <code>Http2Stream</code> sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged <code>PING</code> and <code>SETTINGS</code> frames are all counted towards the current limit. <strong>Default:</strong> <code>10</code>.</li> <li><code>maxHeaderListPairs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of header entries. The minimum value is <code>4</code>. <strong>Default:</strong> <code>128</code>.</li> <li><code>maxOutstandingPings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of outstanding, unacknowledged pings. <strong>Default:</strong> <code>10</code>.</li> <li><code>maxSendHeaderBlockLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a <code>'frameError'</code> event being emitted and the stream being closed and destroyed.</li> <li> <p><code>paddingStrategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Identifies the strategy used for determining the amount of padding to use for <code>HEADERS</code> and <code>DATA</code> frames. <strong>Default:</strong> <code>http2.constants.PADDING_STRATEGY_NONE</code>. Value may be one of:</p> <ul> <li><code>http2.constants.PADDING_STRATEGY_NONE</code> - Specifies that no padding is to be applied.</li> <li><code>http2.constants.PADDING_STRATEGY_MAX</code> - Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied.</li> <li><code>http2.constants.PADDING_STRATEGY_CALLBACK</code> - Specifies that the user provided <code>options.selectPadding()</code> callback is to be used to determine the amount of padding.</li> <li><code>http2.constants.PADDING_STRATEGY_ALIGNED</code> - Will <em>attempt</em> 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 <em>not</em> necessarily be aligned at 8 bytes.</li> </ul> </li> <li><code>peerMaxConcurrentStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of concurrent streams for the remote peer as if a <code>SETTINGS</code> frame had been received. Will be overridden if the remote peer sets its own value for <code>maxConcurrentStreams</code>. <strong>Default:</strong> <code>100</code>.</li> <li><code>selectPadding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> When <code>options.paddingStrategy</code> is equal to <code>http2.constants.PADDING_STRATEGY_CALLBACK</code>, provides the callback function used to determine the padding. See <a href="#http2_using_options_selectpadding">Using <code>options.selectPadding()</code></a>.</li> <li><code>settings</code> <a href="http2.html#http2_settings_object" class="type"><HTTP/2 Settings Object></a> The initial settings to send to the remote peer upon connection.</li> <li>...: Any <a href="tls.html#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a> options can be provided. For servers, the identity options (<code>pfx</code> or <code>key</code>/<code>cert</code>) are usually required.</li> <li><code>origins</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> An array of origin strings to send within an <code>ORIGIN</code> frame immediately following creation of a new server <code>Http2Session</code>.</li> <li><code>unknownProtocolTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies a timeout in milliseconds that a server should wait when an <a href="#http2_event_unknownprotocol"><code>'unknownProtocol'</code></a> event is emitted. If the socket has not been destroyed by that time the server will destroy it. <strong>Default:</strong> <code>10000</code>.</li> </ul> </li> <li><code>onRequestHandler</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> See <a href="#http2_compatibility_api">Compatibility API</a></li> <li>Returns: <a href="http2.html#http2_class_http2secureserver" class="type"><Http2SecureServer></a></li> </ul> <p>Returns a <code>tls.Server</code> instance that creates and manages <code>Http2Session</code> instances.</p> <pre><code class="language-js">const http2 = require('http2'); const fs = require('fs'); const options = { key: fs.readFileSync('server-key.pem'), cert: fs.readFileSync('server-cert.pem') }; // Create a secure HTTP/2 server const server = http2.createSecureServer(options); server.on('stream', (stream, headers) => { stream.respond({ 'content-type': 'text/html', ':status': 200 }); stream.end('<h1>Hello World</h1>'); }); server.listen(80); </code></pre> <h3>http2.connect(authority[, options][, listener])<span><a class="mark" href="#http2_http2_connect_authority_options_listener" id="http2_http2_connect_authority_options_listener">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.24.0</td> <td><p>Added <code>unknownProtocolTimeout</code> option with a default of 10000.</p></td></tr> <tr><td>v10.21.0</td> <td><p>Added <code>maxSettings</code> option with a default of 32.</p></td></tr> <tr><td>v8.9.3</td> <td><p>Added the <code>maxOutstandingPings</code> option with a default limit of 10.</p></td></tr> <tr><td>v8.9.3</td> <td><p>Added the <code>maxHeaderListPairs</code> option with a default limit of 128 header pairs.</p></td></tr> <tr><td>v8.4.0</td> <td><p><span>Added in: v8.4.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>authority</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>maxDeflateDynamicTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum dynamic table size for deflating header fields. <strong>Default:</strong> <code>4Kib</code>.</li> <li><code>maxSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of settings entries per <code>SETTINGS</code> frame. The minimum value allowed is <code>1</code>. <strong>Default:</strong> <code>32</code>.</li> <li><code>maxSessionMemory</code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum memory that the <code>Http2Session</code> is permitted to use. The value is expressed in terms of number of megabytes, e.g. <code>1</code> equal 1 megabyte. The minimum value allowed is <code>1</code>. This is a credit based limit, existing <code>Http2Stream</code>s may cause this limit to be exceeded, but new <code>Http2Stream</code> instances will be rejected while this limit is exceeded. The current number of <code>Http2Stream</code> sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged <code>PING</code> and <code>SETTINGS</code> frames are all counted towards the current limit. <strong>Default:</strong> <code>10</code>.</li> <li><code>maxHeaderListPairs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of header entries. The minimum value is <code>1</code>. <strong>Default:</strong> <code>128</code>.</li> <li><code>maxOutstandingPings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of outstanding, unacknowledged pings. <strong>Default:</strong> <code>10</code>.</li> <li><code>maxReservedRemoteStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> 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.</li> <li><code>maxSendHeaderBlockLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a <code>'frameError'</code> event being emitted and the stream being closed and destroyed.</li> <li> <p><code>paddingStrategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Identifies the strategy used for determining the amount of padding to use for <code>HEADERS</code> and <code>DATA</code> frames. <strong>Default:</strong> <code>http2.constants.PADDING_STRATEGY_NONE</code>. Value may be one of:</p> <ul> <li><code>http2.constants.PADDING_STRATEGY_NONE</code> - Specifies that no padding is to be applied.</li> <li><code>http2.constants.PADDING_STRATEGY_MAX</code> - Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied.</li> <li><code>http2.constants.PADDING_STRATEGY_CALLBACK</code> - Specifies that the user provided <code>options.selectPadding()</code> callback is to be used to determine the amount of padding.</li> <li><code>http2.constants.PADDING_STRATEGY_ALIGNED</code> - Will <em>attempt</em> 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 <em>not</em> necessarily be aligned at 8 bytes.</li> </ul> </li> <li><code>peerMaxConcurrentStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of concurrent streams for the remote peer as if a <code>SETTINGS</code> frame had been received. Will be overridden if the remote peer sets its own value for <code>maxConcurrentStreams</code>. <strong>Default:</strong> <code>100</code>.</li> <li><code>selectPadding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> When <code>options.paddingStrategy</code> is equal to <code>http2.constants.PADDING_STRATEGY_CALLBACK</code>, provides the callback function used to determine the padding. See <a href="#http2_using_options_selectpadding">Using <code>options.selectPadding()</code></a>.</li> <li><code>settings</code> <a href="http2.html#http2_settings_object" class="type"><HTTP/2 Settings Object></a> The initial settings to send to the remote peer upon connection.</li> <li><code>createConnection</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> An optional callback that receives the <code>URL</code> instance passed to <code>connect</code> and the <code>options</code> object, and returns any <a href="stream.html#stream_class_stream_duplex"><code>Duplex</code></a> stream that is to be used as the connection for this session.</li> <li>...: Any <a href="net.html#net_net_connect"><code>net.connect()</code></a> or <a href="tls.html#tls_tls_connect_options_callback"><code>tls.connect()</code></a> options can be provided.</li> <li><code>unknownProtocolTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies a timeout in milliseconds that a server should wait when an <a href="#http2_event_unknownprotocol"><code>'unknownProtocol'</code></a> event is emitted. If the socket has not been destroyed by that time the server will destroy it. <strong>Default:</strong> <code>10000</code>.</li> </ul> </li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="http2.html#http2_class_clienthttp2session" class="type"><ClientHttp2Session></a></li> </ul> <p>Returns a <code>ClientHttp2Session</code> instance.</p> <pre><code class="language-js">const http2 = require('http2'); const client = http2.connect('https://localhost:1234'); /* Use the client */ client.close(); </code></pre> <h3>http2.constants<span><a class="mark" href="#http2_http2_constants" id="http2_http2_constants">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <h4>Error Codes for RST_STREAM and GOAWAY<span><a class="mark" href="#http2_error_codes_for_rst_stream_and_goaway" id="http2_error_codes_for_rst_stream_and_goaway">#</a></span></h4> <p><a id="error_codes"></a></p> <table><thead><tr><th>Value</th><th>Name</th><th>Constant</th></tr></thead><tbody><tr><td><code>0x00</code></td><td>No Error</td><td><code>http2.constants.NGHTTP2_NO_ERROR</code></td></tr><tr><td><code>0x01</code></td><td>Protocol Error</td><td><code>http2.constants.NGHTTP2_PROTOCOL_ERROR</code></td></tr><tr><td><code>0x02</code></td><td>Internal Error</td><td><code>http2.constants.NGHTTP2_INTERNAL_ERROR</code></td></tr><tr><td><code>0x03</code></td><td>Flow Control Error</td><td><code>http2.constants.NGHTTP2_FLOW_CONTROL_ERROR</code></td></tr><tr><td><code>0x04</code></td><td>Settings Timeout</td><td><code>http2.constants.NGHTTP2_SETTINGS_TIMEOUT</code></td></tr><tr><td><code>0x05</code></td><td>Stream Closed</td><td><code>http2.constants.NGHTTP2_STREAM_CLOSED</code></td></tr><tr><td><code>0x06</code></td><td>Frame Size Error</td><td><code>http2.constants.NGHTTP2_FRAME_SIZE_ERROR</code></td></tr><tr><td><code>0x07</code></td><td>Refused Stream</td><td><code>http2.constants.NGHTTP2_REFUSED_STREAM</code></td></tr><tr><td><code>0x08</code></td><td>Cancel</td><td><code>http2.constants.NGHTTP2_CANCEL</code></td></tr><tr><td><code>0x09</code></td><td>Compression Error</td><td><code>http2.constants.NGHTTP2_COMPRESSION_ERROR</code></td></tr><tr><td><code>0x0a</code></td><td>Connect Error</td><td><code>http2.constants.NGHTTP2_CONNECT_ERROR</code></td></tr><tr><td><code>0x0b</code></td><td>Enhance Your Calm</td><td><code>http2.constants.NGHTTP2_ENHANCE_YOUR_CALM</code></td></tr><tr><td><code>0x0c</code></td><td>Inadequate Security</td><td><code>http2.constants.NGHTTP2_INADEQUATE_SECURITY</code></td></tr><tr><td><code>0x0d</code></td><td>HTTP/1.1 Required</td><td><code>http2.constants.NGHTTP2_HTTP_1_1_REQUIRED</code></td></tr></tbody></table> <p>The <code>'timeout'</code> event is emitted when there is no activity on the Server for a given number of milliseconds set using <code>http2server.setTimeout()</code>.</p> <h3>http2.getDefaultSettings()<span><a class="mark" href="#http2_http2_getdefaultsettings" id="http2_http2_getdefaultsettings">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li>Returns: <a href="http2.html#http2_settings_object" class="type"><HTTP/2 Settings Object></a></li> </ul> <p>Returns an object containing the default settings for an <code>Http2Session</code> instance. This method returns a new object instance every time it is called so instances returned may be safely modified for use.</p> <h3>http2.getPackedSettings(settings)<span><a class="mark" href="#http2_http2_getpackedsettings_settings" id="http2_http2_getpackedsettings_settings">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>settings</code> <a href="http2.html#http2_settings_object" class="type"><HTTP/2 Settings Object></a></li> <li>Returns: <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Returns a <code>Buffer</code> instance containing serialized representation of the given HTTP/2 settings as specified in the <a href="https://tools.ietf.org/html/rfc7540">HTTP/2</a> specification. This is intended for use with the <code>HTTP2-Settings</code> header field.</p> <pre><code class="language-js">const http2 = require('http2'); const packed = http2.getPackedSettings({ enablePush: false }); console.log(packed.toString('base64')); // Prints: AAIAAAAA </code></pre> <h3>http2.getUnpackedSettings(buf)<span><a class="mark" href="#http2_http2_getunpackedsettings_buf" id="http2_http2_getunpackedsettings_buf">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>buf</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> The packed settings.</li> <li>Returns: <a href="http2.html#http2_settings_object" class="type"><HTTP/2 Settings Object></a></li> </ul> <p>Returns a <a href="#http2_settings_object">HTTP/2 Settings Object</a> containing the deserialized settings from the given <code>Buffer</code> as generated by <code>http2.getPackedSettings()</code>.</p> <h3>Headers Object<span><a class="mark" href="#http2_headers_object" id="http2_headers_object">#</a></span></h3> <p>Headers are represented as own-properties on JavaScript objects. The property keys will be serialized to lower-case. Property values should be strings (if they are not they will be coerced to strings) or an <code>Array</code> of strings (in order to send more than one value per header field).</p> <pre><code class="language-js">const headers = { ':status': '200', 'content-type': 'text-plain', 'ABC': ['has', 'more', 'than', 'one', 'value'] }; stream.respond(headers); </code></pre> <p>Header objects passed to callback functions will have a <code>null</code> prototype. This means that normal JavaScript object methods such as <code>Object.prototype.toString()</code> and <code>Object.prototype.hasOwnProperty()</code> will not work.</p> <p>For incoming headers:</p> <ul> <li>The <code>:status</code> header is converted to <code>number</code>.</li> <li>Duplicates of <code>:status</code>, <code>:method</code>, <code>:authority</code>, <code>:scheme</code>, <code>:path</code>, <code>:protocol</code>, <code>age</code>, <code>authorization</code>, <code>access-control-allow-credentials</code>, <code>access-control-max-age</code>, <code>access-control-request-method</code>, <code>content-encoding</code>, <code>content-language</code>, <code>content-length</code>, <code>content-location</code>, <code>content-md5</code>, <code>content-range</code>, <code>content-type</code>, <code>date</code>, <code>dnt</code>, <code>etag</code>, <code>expires</code>, <code>from</code>, <code>if-match</code>, <code>if-modified-since</code>, <code>if-none-match</code>, <code>if-range</code>, <code>if-unmodified-since</code>, <code>last-modified</code>, <code>location</code>, <code>max-forwards</code>, <code>proxy-authorization</code>, <code>range</code>, <code>referer</code>,<code>retry-after</code>, <code>tk</code>, <code>upgrade-insecure-requests</code>, <code>user-agent</code> or <code>x-content-type-options</code> are discarded.</li> <li><code>set-cookie</code> is always an array. Duplicates are added to the array.</li> <li>For duplicate <code>cookie</code> headers, the values are joined together with '; '.</li> <li>For all other headers, the values are joined together with ', '.</li> </ul> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream, headers) => { console.log(headers[':path']); console.log(headers.ABC); }); </code></pre> <h3>Settings Object<span><a class="mark" href="#http2_settings_object" id="http2_settings_object">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.9.3</td> <td><p>The <code>maxHeaderListSize</code> setting is now strictly enforced.</p></td></tr> <tr><td>v8.4.0</td> <td><p><span>Added in: v8.4.0</span></p></td></tr> </tbody></table> </details> </div> <p>The <code>http2.getDefaultSettings()</code>, <code>http2.getPackedSettings()</code>, <code>http2.createServer()</code>, <code>http2.createSecureServer()</code>, <code>http2session.settings()</code>, <code>http2session.localSettings</code>, and <code>http2session.remoteSettings</code> APIs either return or receive as input an object that defines configuration settings for an <code>Http2Session</code> object. These objects are ordinary JavaScript objects containing the following properties.</p> <ul> <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 header compression. The minimum allowed value is 0. The maximum allowed value is 2<sup>32</sup>-1. <strong>Default:</strong> <code>4,096 octets</code>.</li> <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 permitted on the <code>Http2Session</code> instances.</li> <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 for stream-level flow control. The minimum allowed value is 0. The maximum allowed value is 2<sup>32</sup>-1. <strong>Default:</strong> <code>65,535 bytes</code>.</li> <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. The minimum allowed value is 16,384. The maximum allowed value is 2<sup>24</sup>-1. <strong>Default:</strong> <code>16,384 bytes</code>.</li> <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 streams permitted on an <code>Http2Session</code>. There is no default value which implies, at least theoretically, 2<sup>31</sup>-1 streams may be open concurrently at any given time in an <code>Http2Session</code>. The minimum value is 0. The maximum allowed value is 2<sup>31</sup>-1.</li> <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) of header list that will be accepted. The minimum allowed value is 0. The maximum allowed value is 2<sup>32</sup>-1. <strong>Default:</strong> <code>65535</code>.</li> <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 Protocol" defined by <a href="https://tools.ietf.org/html/rfc8441">RFC 8441</a> is to be enabled. This setting is only meaningful if sent by the server. Once the <code>enableConnectProtocol</code> setting has been enabled for a given <code>Http2Session</code>, it cannot be disabled.</li> </ul> <p>All additional properties on the settings object are ignored.</p> <h3>Using <code>options.selectPadding()</code><span><a class="mark" href="#http2_using_options_selectpadding" id="http2_using_options_selectpadding">#</a></span></h3> <p>When <code>options.paddingStrategy</code> is equal to <code>http2.constants.PADDING_STRATEGY_CALLBACK</code>, the HTTP/2 implementation will consult the <code>options.selectPadding()</code> callback function, if provided, to determine the specific amount of padding to use per <code>HEADERS</code> and <code>DATA</code> frame.</p> <p>The <code>options.selectPadding()</code> function receives two numeric arguments, <code>frameLen</code> and <code>maxFrameLen</code> and must return a number <code>N</code> such that <code>frameLen <= N <= maxFrameLen</code>.</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer({ paddingStrategy: http2.constants.PADDING_STRATEGY_CALLBACK, selectPadding(frameLen, maxFrameLen) { return maxFrameLen; } }); </code></pre> <p>The <code>options.selectPadding()</code> function is invoked once for <em>every</em> <code>HEADERS</code> and <code>DATA</code> frame. This has a definite noticeable impact on performance.</p> <h3>Error Handling<span><a class="mark" href="#http2_error_handling" id="http2_error_handling">#</a></span></h3> <p>There are several types of error conditions that may arise when using the <code>http2</code> module:</p> <p>Validation errors occur when an incorrect argument, option, or setting value is passed in. These will always be reported by a synchronous <code>throw</code>.</p> <p>State errors occur when an action is attempted at an incorrect time (for instance, attempting to send data on a stream after it has closed). These will be reported using either a synchronous <code>throw</code> or via an <code>'error'</code> event on the <code>Http2Stream</code>, <code>Http2Session</code> or HTTP/2 Server objects, depending on where and when the error occurs.</p> <p>Internal errors occur when an HTTP/2 session fails unexpectedly. These will be reported via an <code>'error'</code> event on the <code>Http2Session</code> or HTTP/2 Server objects.</p> <p>Protocol errors occur when various HTTP/2 protocol constraints are violated. These will be reported using either a synchronous <code>throw</code> or via an <code>'error'</code> event on the <code>Http2Stream</code>, <code>Http2Session</code> or HTTP/2 Server objects, depending on where and when the error occurs.</p> <h3>Invalid character handling in header names and values<span><a class="mark" href="#http2_invalid_character_handling_in_header_names_and_values" id="http2_invalid_character_handling_in_header_names_and_values">#</a></span></h3> <p>The HTTP/2 implementation applies stricter handling of invalid characters in HTTP header names and values than the HTTP/1 implementation.</p> <p>Header field names are <em>case-insensitive</em> and are transmitted over the wire strictly as lower-case strings. The API provided by Node.js allows header names to be set as mixed-case strings (e.g. <code>Content-Type</code>) but will convert those to lower-case (e.g. <code>content-type</code>) upon transmission.</p> <p>Header field-names <em>must only</em> contain one or more of the following ASCII characters: <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>, <code>-</code>, <code>.</code>, <code>^</code>, <code>_</code>, <code>`</code> (backtick), <code>|</code>, and <code>~</code>.</p> <p>Using invalid characters within an HTTP header field name will cause the stream to be closed with a protocol error being reported.</p> <p>Header field values are handled with more leniency but <em>should</em> not contain new-line or carriage return characters and <em>should</em> be limited to US-ASCII characters, per the requirements of the HTTP specification.</p> <h3>Push streams on the client<span><a class="mark" href="#http2_push_streams_on_the_client" id="http2_push_streams_on_the_client">#</a></span></h3> <p>To receive pushed streams on the client, set a listener for the <code>'stream'</code> event on the <code>ClientHttp2Session</code>:</p> <pre><code class="language-js">const http2 = require('http2'); const client = http2.connect('http://localhost'); client.on('stream', (pushedStream, requestHeaders) => { pushedStream.on('push', (responseHeaders) => { // process response headers }); pushedStream.on('data', (chunk) => { /* handle pushed data */ }); }); const req = client.request({ ':path': '/' }); </code></pre> <h3>Supporting the CONNECT method<span><a class="mark" href="#http2_supporting_the_connect_method" id="http2_supporting_the_connect_method">#</a></span></h3> <p>The <code>CONNECT</code> method is used to allow an HTTP/2 server to be used as a proxy for TCP/IP connections.</p> <p>A simple TCP Server:</p> <pre><code class="language-js">const net = require('net'); const server = net.createServer((socket) => { let name = ''; socket.setEncoding('utf8'); socket.on('data', (chunk) => name += chunk); socket.on('end', () => socket.end(`hello ${name}`)); }); server.listen(8000); </code></pre> <p>An HTTP/2 CONNECT proxy:</p> <pre><code class="language-js">const http2 = require('http2'); const { NGHTTP2_REFUSED_STREAM } = http2.constants; const net = require('net'); const proxy = http2.createServer(); proxy.on('stream', (stream, headers) => { if (headers[':method'] !== 'CONNECT') { // Only accept CONNECT requests stream.close(NGHTTP2_REFUSED_STREAM); return; } const auth = new URL(`tcp://${headers[':authority']}`); // It's a very good idea to verify that hostname and port are // things this proxy should be connecting to. const socket = net.connect(auth.port, auth.hostname, () => { stream.respond(); socket.pipe(stream); stream.pipe(socket); }); socket.on('error', (error) => { stream.close(http2.constants.NGHTTP2_CONNECT_ERROR); }); }); proxy.listen(8001); </code></pre> <p>An HTTP/2 CONNECT client:</p> <pre><code class="language-js">const http2 = require('http2'); const client = http2.connect('http://localhost:8001'); // Must not specify the ':path' and ':scheme' headers // for CONNECT requests or an error will be thrown. const req = client.request({ ':method': 'CONNECT', ':authority': `localhost:${port}` }); req.on('response', (headers) => { console.log(headers[http2.constants.HTTP2_HEADER_STATUS]); }); let data = ''; req.setEncoding('utf8'); req.on('data', (chunk) => data += chunk); req.on('end', () => { console.log(`The server says: ${data}`); client.close(); }); req.end('Jane'); </code></pre> <h3>The Extended CONNECT Protocol<span><a class="mark" href="#http2_the_extended_connect_protocol" id="http2_the_extended_connect_protocol">#</a></span></h3> <p><a href="https://tools.ietf.org/html/rfc8441">RFC 8441</a> defines an "Extended CONNECT Protocol" extension to HTTP/2 that may be used to bootstrap the use of an <code>Http2Stream</code> using the <code>CONNECT</code> method as a tunnel for other communication protocols (such as WebSockets).</p> <p>The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using the <code>enableConnectProtocol</code> setting:</p> <pre><code class="language-js">const http2 = require('http2'); const settings = { enableConnectProtocol: true }; const server = http2.createServer({ settings }); </code></pre> <p>Once the client receives the <code>SETTINGS</code> frame from the server indicating that the extended CONNECT may be used, it may send <code>CONNECT</code> requests that use the <code>':protocol'</code> HTTP/2 pseudo-header:</p> <pre><code class="language-js">const http2 = require('http2'); const client = http2.connect('http://localhost:8080'); client.on('remoteSettings', (settings) => { if (settings.enableConnectProtocol) { const req = client.request({ ':method': 'CONNECT', ':protocol': 'foo' }); // ... } }); </code></pre> <h2>Compatibility API<span><a class="mark" href="#http2_compatibility_api" id="http2_compatibility_api">#</a></span></h2> <p>The Compatibility API has the goal of providing a similar developer experience of HTTP/1 when using HTTP/2, making it possible to develop applications that support both <a href="http.html">HTTP/1</a> and HTTP/2. This API targets only the <strong>public API</strong> of the <a href="http.html">HTTP/1</a>. However many modules use internal methods or state, and those <em>are not supported</em> as it is a completely different implementation.</p> <p>The following example creates an HTTP/2 server using the compatibility API:</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Foo', 'bar'); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('ok'); }); </code></pre> <p>In order to create a mixed <a href="https.html">HTTPS</a> and HTTP/2 server, refer to the <a href="#http2_alpn_negotiation">ALPN negotiation</a> section. Upgrading from non-tls HTTP/1 servers is not supported.</p> <p>The HTTP/2 compatibility API is composed of <a href=""><code>Http2ServerRequest</code></a> and <a href=""><code>Http2ServerResponse</code></a>. They aim at API compatibility with HTTP/1, but they do not hide the differences between the protocols. As an example, the status message for HTTP codes is ignored.</p> <h3>ALPN negotiation<span><a class="mark" href="#http2_alpn_negotiation" id="http2_alpn_negotiation">#</a></span></h3> <p>ALPN negotiation allows supporting both <a href="https.html">HTTPS</a> and HTTP/2 over the same socket. The <code>req</code> and <code>res</code> objects can be either HTTP/1 or HTTP/2, and an application <strong>must</strong> restrict itself to the public API of <a href="http.html">HTTP/1</a>, and detect if it is possible to use the more advanced features of HTTP/2.</p> <p>The following example creates a server that supports both protocols:</p> <pre><code class="language-js">const { createSecureServer } = require('http2'); const { readFileSync } = require('fs'); const cert = readFileSync('./cert.pem'); const key = readFileSync('./key.pem'); const server = createSecureServer( { cert, key, allowHTTP1: true }, onRequest ).listen(4443); function onRequest(req, res) { // detects if it is a HTTPS request or HTTP/2 const { socket: { alpnProtocol } } = req.httpVersion === '2.0' ? req.stream.session : req; res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ alpnProtocol, httpVersion: req.httpVersion })); } </code></pre> <p>The <code>'request'</code> event works identically on both <a href="https.html">HTTPS</a> and HTTP/2.</p> <h3>Class: http2.Http2ServerRequest<span><a class="mark" href="#http2_class_http2_http2serverrequest" id="http2_class_http2_http2serverrequest">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>A <code>Http2ServerRequest</code> object is created by <a href="#http2_class_http2server"><code>http2.Server</code></a> or <a href="#http2_class_http2secureserver"><code>http2.SecureServer</code></a> and passed as the first argument to the <a href="#http2_event_request"><code>'request'</code></a> event. It may be used to access a request status, headers, and data.</p> <p>It implements the <a href="stream.html#stream_class_stream_readable">Readable Stream</a> interface, as well as the following additional events, methods, and properties.</p> <h4>Event: 'aborted'<span><a class="mark" href="#http2_event_aborted_1" id="http2_event_aborted_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'aborted'</code> event is emitted whenever a <code>Http2ServerRequest</code> instance is abnormally aborted in mid-communication.</p> <p>The <code>'aborted'</code> event will only be emitted if the <code>Http2ServerRequest</code> writable side has not been ended.</p> <h4>Event: 'close'<span><a class="mark" href="#http2_event_close_2" id="http2_event_close_2">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>Indicates that the underlying <a href="#http2_class_http2stream"><code>Http2Stream</code></a> was closed. Just like <code>'end'</code>, this event occurs only once per response.</p> <h4>request.aborted<span><a class="mark" href="#http2_request_aborted" id="http2_request_aborted">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.1.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The <code>request.aborted</code> property will be <code>true</code> if the request has been aborted.</p> <h4>request.authority<span><a class="mark" href="#http2_request_authority" id="http2_request_authority">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The request authority pseudo header field. It can also be accessed via <code>req.headers[':authority']</code>.</p> <h4>request.destroy([error])<span><a class="mark" href="#http2_request_destroy_error" id="http2_request_destroy_error">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>Calls <code>destroy()</code> on the <a href="#http2_class_http2stream"><code>Http2Stream</code></a> that received the <a href="#http2_class_http2_http2serverrequest"><code>Http2ServerRequest</code></a>. If <code>error</code> is provided, an <code>'error'</code> event is emitted and <code>error</code> is passed as an argument to any listeners on the event.</p> <p>It does nothing if the stream was already destroyed.</p> <h4>request.headers<span><a class="mark" href="#http2_request_headers" id="http2_request_headers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The request/response headers object.</p> <p>Key-value pairs of header names and values. Header names are lower-cased.</p> <pre><code class="language-js">// Prints something like: // // { 'user-agent': 'curl/7.22.0', // host: '127.0.0.1:8000', // accept: '*/*' } console.log(request.headers); </code></pre> <p>See <a href="#http2_headers_object">HTTP/2 Headers Object</a>.</p> <p>In HTTP/2, the request path, hostname, protocol, and method are represented as special headers prefixed with the <code>:</code> character (e.g. <code>':path'</code>). These special headers will be included in the <code>request.headers</code> object. Care must be taken not to inadvertently modify these special headers or errors may occur. For instance, removing all headers from the request will cause errors to occur:</p> <pre><code class="language-js">removeAllHeaders(request.headers); assert(request.url); // Fails because the :path header has been removed </code></pre> <h4>request.httpVersion<span><a class="mark" href="#http2_request_httpversion" id="http2_request_httpversion">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server. Returns <code>'2.0'</code>.</p> <p>Also <code>message.httpVersionMajor</code> is the first integer and <code>message.httpVersionMinor</code> is the second.</p> <h4>request.method<span><a class="mark" href="#http2_request_method" id="http2_request_method">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The request method as a string. Read-only. Examples: <code>'GET'</code>, <code>'DELETE'</code>.</p> <h4>request.rawHeaders<span><a class="mark" href="#http2_request_rawheaders" id="http2_request_rawheaders">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>The raw request/response headers list exactly as they were received.</p> <p>Note that the keys and values are in the same list. It is <em>not</em> a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values.</p> <p>Header names are not lowercased, and duplicates are not merged.</p> <pre><code class="language-js">// Prints something like: // // [ 'user-agent', // 'this is invalid because there can be only one', // 'User-Agent', // 'curl/7.22.0', // 'Host', // '127.0.0.1:8000', // 'ACCEPT', // '*/*' ] console.log(request.rawHeaders); </code></pre> <h4>request.rawTrailers<span><a class="mark" href="#http2_request_rawtrailers" id="http2_request_rawtrailers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>The raw request/response trailer keys and values exactly as they were received. Only populated at the <code>'end'</code> event.</p> <h4>request.scheme<span><a class="mark" href="#http2_request_scheme" id="http2_request_scheme">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The request scheme pseudo header field indicating the scheme portion of the target URL.</p> <h4>request.setTimeout(msecs, callback)<span><a class="mark" href="#http2_request_settimeout_msecs_callback" id="http2_request_settimeout_msecs_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="http2.html#http2_class_http2_http2serverrequest" class="type"><http2.Http2ServerRequest></a></li> </ul> <p>Sets the <a href=""><code>Http2Stream</code></a>'s timeout value to <code>msecs</code>. If a callback is provided, then it is added as a listener on the <code>'timeout'</code> event on the response object.</p> <p>If no <code>'timeout'</code> listener is added to the request, the response, or the server, then <a href=""><code>Http2Stream</code></a>s are destroyed when they time out. If a handler is assigned to the request, the response, or the server's <code>'timeout'</code> events, timed out sockets must be handled explicitly.</p> <h4>request.socket<span><a class="mark" href="#http2_request_socket" id="http2_request_socket">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="net.html#net_class_net_socket" class="type"><net.Socket></a> | <a href="tls.html#tls_class_tls_tlssocket" class="type"><tls.TLSSocket></a></li> </ul> <p>Returns a <code>Proxy</code> object that acts as a <code>net.Socket</code> (or <code>tls.TLSSocket</code>) but applies getters, setters, and methods based on HTTP/2 logic.</p> <p><code>destroyed</code>, <code>readable</code>, and <code>writable</code> properties will be retrieved from and set on <code>request.stream</code>.</p> <p><code>destroy</code>, <code>emit</code>, <code>end</code>, <code>on</code> and <code>once</code> methods will be called on <code>request.stream</code>.</p> <p><code>setTimeout</code> method will be called on <code>request.stream.session</code>.</p> <p><code>pause</code>, <code>read</code>, <code>resume</code>, and <code>write</code> will throw an error with code <code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code>. See <a href="#http2_http2session_and_sockets"><code>Http2Session</code> and Sockets</a> for more information.</p> <p>All other interactions will be routed directly to the socket. With TLS support, use <a href="tls.html#tls_tlssocket_getpeercertificate_detailed"><code>request.socket.getPeerCertificate()</code></a> to obtain the client's authentication details.</p> <h4>request.stream<span><a class="mark" href="#http2_request_stream" id="http2_request_stream">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="http2.html#http2_class_http2stream" class="type"><Http2Stream></a></li> </ul> <p>The <a href="#http2_class_http2stream"><code>Http2Stream</code></a> object backing the request.</p> <h4>request.trailers<span><a class="mark" href="#http2_request_trailers" id="http2_request_trailers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The request/response trailers object. Only populated at the <code>'end'</code> event.</p> <h4>request.url<span><a class="mark" href="#http2_request_url" id="http2_request_url">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Request URL string. This contains only the URL that is present in the actual HTTP request. If the request is:</p> <pre><code class="language-txt">GET /status?name=ryan HTTP/1.1\r\n Accept: text/plain\r\n \r\n </code></pre> <p>Then <code>request.url</code> will be:</p> <!-- eslint-disable semi --> <pre><code class="language-js">'/status?name=ryan' </code></pre> <p>To parse the url into its parts <code>require('url').parse(request.url)</code> can be used:</p> <pre><code class="language-txt">$ node > require('url').parse('/status?name=ryan') Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: '?name=ryan', query: 'name=ryan', pathname: '/status', path: '/status?name=ryan', href: '/status?name=ryan' } </code></pre> <p>To extract the parameters from the query string, the <code>require('querystring').parse</code> function can be used, or <code>true</code> can be passed as the second argument to <code>require('url').parse</code>.</p> <pre><code class="language-txt">$ node > require('url').parse('/status?name=ryan', true) Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: '?name=ryan', query: { name: 'ryan' }, pathname: '/status', path: '/status?name=ryan', href: '/status?name=ryan' } </code></pre> <h3>Class: http2.Http2ServerResponse<span><a class="mark" href="#http2_class_http2_http2serverresponse" id="http2_class_http2_http2serverresponse">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the <a href="#http2_event_request"><code>'request'</code></a> event.</p> <p>The response inherits from <a href="stream.html#stream_stream">Stream</a>, and additionally implements the following:</p> <h4>Event: 'close'<span><a class="mark" href="#http2_event_close_3" id="http2_event_close_3">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>Indicates that the underlying <a href=""><code>Http2Stream</code></a> was terminated before <a href="#http2_response_end_data_encoding_callback"><code>response.end()</code></a> was called or able to flush.</p> <h4>Event: 'finish'<span><a class="mark" href="#http2_event_finish" id="http2_event_finish">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>Emitted when the response has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the HTTP/2 multiplexing for transmission over the network. It does not imply that the client has received anything yet.</p> <p>After this event, no more events will be emitted on the response object.</p> <h4>response.addTrailers(headers)<span><a class="mark" href="#http2_response_addtrailers_headers" id="http2_response_addtrailers_headers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>This method adds HTTP trailing headers (a header but at the end of the message) to the response.</p> <p>Attempting to set a header field name or value that contains invalid characters will result in a <a href="errors.html#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p> <h4>response.connection<span><a class="mark" href="#http2_response_connection" id="http2_response_connection">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="net.html#net_class_net_socket" class="type"><net.Socket></a> | <a href="tls.html#tls_class_tls_tlssocket" class="type"><tls.TLSSocket></a></li> </ul> <p>See <a href="#http2_response_socket"><code>response.socket</code></a>.</p> <h4>response.end([data][, encoding][, callback])<span><a class="mark" href="#http2_response_end_data_encoding_callback" id="http2_response_end_data_encoding_callback">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>This method now returns a reference to <code>ServerResponse</code>.</p></td></tr> <tr><td>v8.4.0</td> <td><p><span>Added in: v8.4.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, <code>response.end()</code>, MUST be called on each response.</p> <p>If <code>data</code> is specified, it is equivalent to calling <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> <p>If <code>callback</code> is specified, it will be called when the response stream is finished.</p> <h4>response.finished<span><a class="mark" href="#http2_response_finished" id="http2_response_finished">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Boolean value that indicates whether the response has completed. Starts as <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> <h4>response.getHeader(name)<span><a class="mark" href="#http2_response_getheader_name" id="http2_response_getheader_name">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Reads out a header that has already been queued but not sent to the client. Note that the name is case insensitive.</p> <pre><code class="language-js">const contentType = response.getHeader('content-type'); </code></pre> <h4>response.getHeaderNames()<span><a class="mark" href="#http2_response_getheadernames" id="http2_response_getheadernames">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>Returns an array containing the unique names of the current outgoing headers. All header names are lowercase.</p> <pre><code class="language-js">response.setHeader('Foo', 'bar'); response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); const headerNames = response.getHeaderNames(); // headerNames === ['foo', 'set-cookie'] </code></pre> <h4>response.getHeaders()<span><a class="mark" href="#http2_response_getheaders" id="http2_response_getheaders">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related http module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.</p> <p>The object returned by the <code>response.getHeaders()</code> method <em>does not</em> prototypically inherit from the JavaScript <code>Object</code>. This means that typical <code>Object</code> methods such as <code>obj.toString()</code>, <code>obj.hasOwnProperty()</code>, and others are not defined and <em>will not work</em>.</p> <pre><code class="language-js">response.setHeader('Foo', 'bar'); response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); const headers = response.getHeaders(); // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } </code></pre> <h4>response.hasHeader(name)<span><a class="mark" href="#http2_response_hasheader_name" id="http2_response_hasheader_name">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the header identified by <code>name</code> is currently set in the outgoing headers. Note that the header name matching is case-insensitive.</p> <pre><code class="language-js">const hasContentType = response.hasHeader('content-type'); </code></pre> <h4>response.headersSent<span><a class="mark" href="#http2_response_headerssent" id="http2_response_headerssent">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>True if headers were sent, false otherwise (read-only).</p> <h4>response.removeHeader(name)<span><a class="mark" href="#http2_response_removeheader_name" id="http2_response_removeheader_name">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Removes a header that has been queued for implicit sending.</p> <pre><code class="language-js">response.removeHeader('Content-Encoding'); </code></pre> <h4>response.sendDate<span><a class="mark" href="#http2_response_senddate" id="http2_response_senddate">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers. Defaults to true.</p> <p>This should only be disabled for testing; HTTP requires the Date header in responses.</p> <h4>response.setHeader(name, value)<span><a class="mark" href="#http2_response_setheader_name_value" id="http2_response_setheader_name_value">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here to send multiple headers with the same name.</p> <pre><code class="language-js">response.setHeader('Content-Type', 'text/html'); </code></pre> <p>or</p> <pre><code class="language-js">response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); </code></pre> <p>Attempting to set a header field name or value that contains invalid characters will result in a <a href="errors.html#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p> <p>When headers have been set with <a href="#http2_response_setheader_name_value"><code>response.setHeader()</code></a>, they will be merged with any headers passed to <a href="#http2_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a>, with the headers passed to <a href="#http2_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> given precedence.</p> <pre><code class="language-js">// returns content-type = text/plain const server = http2.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Foo', 'bar'); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('ok'); }); </code></pre> <h4>response.setTimeout(msecs[, callback])<span><a class="mark" href="#http2_response_settimeout_msecs_callback" id="http2_response_settimeout_msecs_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="http2.html#http2_class_http2_http2serverresponse" class="type"><http2.Http2ServerResponse></a></li> </ul> <p>Sets the <a href=""><code>Http2Stream</code></a>'s timeout value to <code>msecs</code>. If a callback is provided, then it is added as a listener on the <code>'timeout'</code> event on the response object.</p> <p>If no <code>'timeout'</code> listener is added to the request, the response, or the server, then <a href=""><code>Http2Stream</code></a>s are destroyed when they time out. If a handler is assigned to the request, the response, or the server's <code>'timeout'</code> events, timed out sockets must be handled explicitly.</p> <h4>response.socket<span><a class="mark" href="#http2_response_socket" id="http2_response_socket">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="net.html#net_class_net_socket" class="type"><net.Socket></a> | <a href="tls.html#tls_class_tls_tlssocket" class="type"><tls.TLSSocket></a></li> </ul> <p>Returns a <code>Proxy</code> object that acts as a <code>net.Socket</code> (or <code>tls.TLSSocket</code>) but applies getters, setters, and methods based on HTTP/2 logic.</p> <p><code>destroyed</code>, <code>readable</code>, and <code>writable</code> properties will be retrieved from and set on <code>response.stream</code>.</p> <p><code>destroy</code>, <code>emit</code>, <code>end</code>, <code>on</code> and <code>once</code> methods will be called on <code>response.stream</code>.</p> <p><code>setTimeout</code> method will be called on <code>response.stream.session</code>.</p> <p><code>pause</code>, <code>read</code>, <code>resume</code>, and <code>write</code> will throw an error with code <code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code>. See <a href="#http2_http2session_and_sockets"><code>Http2Session</code> and Sockets</a> for more information.</p> <p>All other interactions will be routed directly to the socket.</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer((req, res) => { const ip = req.socket.remoteAddress; const port = req.socket.remotePort; res.end(`Your IP address is ${ip} and your source port is ${port}.`); }).listen(3000); </code></pre> <h4>response.statusCode<span><a class="mark" href="#http2_response_statuscode" id="http2_response_statuscode">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>When using implicit headers (not calling <a href="#http2_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> explicitly), this property controls the status code that will be sent to the client when the headers get flushed.</p> <pre><code class="language-js">response.statusCode = 404; </code></pre> <p>After response header was sent to the client, this property indicates the status code which was sent out.</p> <h4>response.statusMessage<span><a class="mark" href="#http2_response_statusmessage" id="http2_response_statusmessage">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Status message is not supported by HTTP/2 (RFC7540 8.1.2.4). It returns an empty string.</p> <h4>response.stream<span><a class="mark" href="#http2_response_stream" id="http2_response_stream">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="http2.html#http2_class_http2stream" class="type"><Http2Stream></a></li> </ul> <p>The <a href="#http2_class_http2stream"><code>Http2Stream</code></a> object backing the response.</p> <h4>response.write(chunk[, encoding][, callback])<span><a class="mark" href="#http2_response_write_chunk_encoding_callback" id="http2_response_write_chunk_encoding_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>If this method is called and <a href="#http2_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> has not been called, it will switch to implicit header mode and flush the implicit headers.</p> <p>This sends a chunk of the response body. This method may be called multiple times to provide successive parts of the body.</p> <p>Note that in the <code>http</code> module, the response body is omitted when the request is a HEAD request. Similarly, the <code>204</code> and <code>304</code> responses <em>must not</em> include a message body.</p> <p><code>chunk</code> can be a string or a buffer. If <code>chunk</code> is a string, the second parameter specifies how to encode it into a byte stream. By default the <code>encoding</code> is <code>'utf8'</code>. <code>callback</code> will be called when this chunk of data is flushed.</p> <p>This is the raw HTTP body and has nothing to do with higher-level multi-part body encodings that may be used.</p> <p>The first time <a href="#http2_response_write_chunk_encoding_callback"><code>response.write()</code></a> is called, it will send the buffered header information and the first chunk of the body to the client. The second time <a href="#http2_response_write_chunk_encoding_callback"><code>response.write()</code></a> is called, Node.js assumes data will be streamed, and sends the new data separately. That is, the response is buffered up to the first chunk of the body.</p> <p>Returns <code>true</code> if the entire data was flushed successfully to the kernel buffer. Returns <code>false</code> if all or part of the data was queued in user memory. <code>'drain'</code> will be emitted when the buffer is free again.</p> <h4>response.writeContinue()<span><a class="mark" href="#http2_response_writecontinue" id="http2_response_writecontinue">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>Sends a status <code>100 Continue</code> to the client, indicating that the request body should be sent. See the <a href="#http2_event_checkcontinue"><code>'checkContinue'</code></a> event on <code>Http2Server</code> and <code>Http2SecureServer</code>.</p> <h4>response.writeHead(statusCode[, statusMessage][, headers])<span><a class="mark" href="#http2_response_writehead_statuscode_statusmessage_headers" id="http2_response_writehead_statuscode_statusmessage_headers">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.17.0</td> <td><p>Return <code>this</code> from <code>writeHead()</code> to allow chaining with <code>end()</code>.</p></td></tr> <tr><td>v8.4.0</td> <td><p><span>Added in: v8.4.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>statusCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>statusMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li>Returns: <a href="http2.html#http2_class_http2_http2serverresponse" class="type"><http2.Http2ServerResponse></a></li> </ul> <p>Sends a response header to the request. The status code is a 3-digit HTTP status code, like <code>404</code>. The last argument, <code>headers</code>, are the response headers.</p> <p>Returns a reference to the <code>Http2ServerResponse</code>, so that calls can be chained.</p> <p>For compatibility with <a href="http.html">HTTP/1</a>, a human-readable <code>statusMessage</code> may be passed as the second argument. However, because the <code>statusMessage</code> has no meaning within HTTP/2, the argument will have no effect and a process warning will be emitted.</p> <pre><code class="language-js">const body = 'hello world'; response.writeHead(200, { 'Content-Length': Buffer.byteLength(body), 'Content-Type': 'text/plain' }); </code></pre> <p>Note that Content-Length is given in bytes not characters. The <code>Buffer.byteLength()</code> API may be used to determine the number of bytes in a given encoding. On outbound messages, Node.js does not check if Content-Length and the length of the body being transmitted are equal or not. However, when receiving messages, Node.js will automatically reject messages when the Content-Length does not match the actual payload size.</p> <p>This method may be called at most one time on a message before <a href="#http2_response_end_data_encoding_callback"><code>response.end()</code></a> is called.</p> <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 this, the implicit/mutable headers will be calculated and call this function.</p> <p>When headers have been set with <a href="#http2_response_setheader_name_value"><code>response.setHeader()</code></a>, they will be merged with any headers passed to <a href="#http2_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a>, with the headers passed to <a href="#http2_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> given precedence.</p> <pre><code class="language-js">// returns content-type = text/plain const server = http2.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Foo', 'bar'); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('ok'); }); </code></pre> <p>Attempting to set a header field name or value that contains invalid characters will result in a <a href="errors.html#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p> <h4>response.createPushResponse(headers, callback)<span><a class="mark" href="#http2_response_createpushresponse_headers_callback" id="http2_response_createpushresponse_headers_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>headers</code> <a href="http2.html#http2_headers_object" class="type"><HTTP/2 Headers Object></a> An object describing the headers</li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Called once <code>http2stream.pushStream()</code> is finished, or either when the attempt to create the pushed <code>Http2Stream</code> has failed or has been rejected, or the state of <code>Http2ServerRequest</code> is closed prior to calling the <code>http2stream.pushStream()</code> method</p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>stream</code> <a href="http2.html#http2_class_serverhttp2stream" class="type"><ServerHttp2Stream></a> The newly-created <code>ServerHttp2Stream</code> object</li> </ul> </li> </ul> <p>Call <a href="#http2_http2stream_pushstream_headers_options_callback"><code>http2stream.pushStream()</code></a> with the given headers, and wrap the given <a href="#http2_class_http2stream"><code>Http2Stream</code></a> on a newly created <code>Http2ServerResponse</code> as the callback parameter if successful. When <code>Http2ServerRequest</code> is closed, the callback is called with an error <code>ERR_HTTP2_INVALID_STREAM</code>.</p> <h2>Collecting HTTP/2 Performance Metrics<span><a class="mark" href="#http2_collecting_http_2_performance_metrics" id="http2_collecting_http_2_performance_metrics">#</a></span></h2> <p>The <a href="perf_hooks.html">Performance Observer</a> API can be used to collect basic performance metrics for each <code>Http2Session</code> and <code>Http2Stream</code> instance.</p> <pre><code class="language-js">const { PerformanceObserver } = require('perf_hooks'); const obs = new PerformanceObserver((items) => { const entry = items.getEntries()[0]; console.log(entry.entryType); // prints 'http2' if (entry.name === 'Http2Session') { // entry contains statistics about the Http2Session } else if (entry.name === 'Http2Stream') { // entry contains statistics about the Http2Stream } }); obs.observe({ entryTypes: ['http2'] }); </code></pre> <p>The <code>entryType</code> property of the <code>PerformanceEntry</code> will be equal to <code>'http2'</code>.</p> <p>The <code>name</code> property of the <code>PerformanceEntry</code> will be equal to either <code>'Http2Stream'</code> or <code>'Http2Session'</code>.</p> <p>If <code>name</code> is equal to <code>Http2Stream</code>, the <code>PerformanceEntry</code> will contain the following additional properties:</p> <ul> <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 <code>Http2Stream</code>.</li> <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 <code>Http2Stream</code>.</li> <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> <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 <code>PerformanceEntry</code> <code>startTime</code> and the reception of the first <code>DATA</code> frame.</li> <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 the <code>PerformanceEntry</code> <code>startTime</code> and sending of the first <code>DATA</code> frame.</li> <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 <code>PerformanceEntry</code> <code>startTime</code> and the reception of the first header.</li> </ul> <p>If <code>name</code> is equal to <code>Http2Session</code>, the <code>PerformanceEntry</code> will contain the following additional properties:</p> <ul> <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> <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> <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 <code>Http2Session</code>.</li> <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> <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 open during the lifetime of the <code>Http2Session</code>.</li> <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 of a <code>PING</code> frame and the reception of its acknowledgment. Only present if a <code>PING</code> frame has been sent on the <code>Http2Session</code>.</li> <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 all <code>Http2Stream</code> instances.</li> <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 the <code>Http2Session</code>.</li> <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 <code>Http2Session</code>.</li> </ul> </div> </div> </div> <script src="assets/sh_main.js"></script> <script src="assets/sh_javascript.min.js"></script> <script>highlight(undefined, undefined, 'pre');</script> </body> </html>