- Assertion testing
- Async hooks
- Buffer
- C++ Addons
- C/C++ Addons with N-API
- C++ Embedder API
- Child Processes
- Cluster
- Command line options
- Console
- Crypto
- Debugger
- Deprecated APIs
- DNS
- Domain
- Errors
- Events
- File system
- Globals
- HTTP
- HTTP/2
- HTTPS
- Inspector
- Internationalization
- Modules: CommonJS modules
- Modules: ECMAScript modules
- Modules:
moduleAPI - Modules: Packages
- Net
- OS
- Path
- Performance hooks
- Policies
- Process
- Punycode
- Query strings
- Readline
- REPL
- Report
- Stream
- String decoder
- Timers
- TLS/SSL
- Trace events
- TTY
- UDP/datagram
- URL
- Utilities
- V8
- VM
- WASI
- Worker threads
- Zlib
Node.js v12.22.12 Documentation
Table of Contents
- HTTP/2
- Core API
- Server-side example
- Client-side example
- Class:
Http2SessionHttp2Sessionand sockets- Event:
'close' - Event:
'connect' - Event:
'error' - Event:
'frameError' - Event:
'goaway' - Event:
'localSettings' - Event:
'ping' - Event:
'remoteSettings' - Event:
'stream' - Event:
'timeout' http2session.alpnProtocolhttp2session.close([callback])http2session.closedhttp2session.connectinghttp2session.destroy([error][, code])http2session.destroyedhttp2session.encryptedhttp2session.goaway([code[, lastStreamID[, opaqueData]]])http2session.localSettingshttp2session.originSethttp2session.pendingSettingsAckhttp2session.ping([payload, ]callback)http2session.ref()http2session.remoteSettingshttp2session.setTimeout(msecs, callback)http2session.sockethttp2session.statehttp2session.settings([settings][, callback])http2session.typehttp2session.unref()
- Class:
ServerHttp2Session - Class:
ClientHttp2Session - Class:
Http2StreamHttp2StreamLifecycle- Event:
'aborted' - Event:
'close' - Event:
'error' - Event:
'frameError' - Event:
'ready' - Event:
'timeout' - Event:
'trailers' - Event:
'wantTrailers' http2stream.abortedhttp2stream.bufferSizehttp2stream.close(code[, callback])http2stream.closedhttp2stream.destroyedhttp2stream.endAfterHeadershttp2stream.idhttp2stream.pendinghttp2stream.priority(options)http2stream.rstCodehttp2stream.sentHeadershttp2stream.sentInfoHeadershttp2stream.sentTrailershttp2stream.sessionhttp2stream.setTimeout(msecs, callback)http2stream.statehttp2stream.sendTrailers(headers)
- Class:
ClientHttp2Stream - Class:
ServerHttp2Stream - Class:
Http2Server - Event:
'connection' - Class:
Http2SecureServer - Event:
'connection' http2.createServer(options[, onRequestHandler])http2.createSecureServer(options[, onRequestHandler])http2.connect(authority[, options][, listener])http2.constantshttp2.getDefaultSettings()http2.getPackedSettings([settings])http2.getUnpackedSettings(buf)- Headers object
- Settings object
- Using
options.selectPadding() - Error handling
- Invalid character handling in header names and values
- Push streams on the client
- Supporting the
CONNECTmethod - The extended
CONNECTprotocol
- Compatibility API
- ALPN negotiation
- Class:
http2.Http2ServerRequest- Event:
'aborted' - Event:
'close' request.abortedrequest.authorityrequest.completerequest.destroy([error])request.headersrequest.httpVersionrequest.methodrequest.rawHeadersrequest.rawTrailersrequest.schemerequest.setTimeout(msecs, callback)request.socketrequest.streamrequest.trailersrequest.url
- Event:
- Class:
http2.Http2ServerResponse- Event:
'close' - Event:
'finish' response.addTrailers(headers)response.connectionresponse.end([data[, encoding]][, callback])response.finishedresponse.getHeader(name)response.getHeaderNames()response.getHeaders()response.hasHeader(name)response.headersSentresponse.removeHeader(name)response.sendDateresponse.setHeader(name, value)response.setTimeout(msecs[, callback])response.socketresponse.statusCoderesponse.statusMessageresponse.streamresponse.writableEndedresponse.write(chunk[, encoding][, callback])response.writeContinue()response.writeHead(statusCode[, statusMessage][, headers])response.createPushResponse(headers, callback)
- Event:
- Collecting HTTP/2 performance metrics
- Core API
HTTP/2#
Source Code: lib/http2.js
The http2 module provides an implementation of the HTTP/2 protocol. It
can be accessed using:
const http2 = require('http2');
Core API#
The Core API provides a low-level interface designed specifically around support for HTTP/2 protocol features. It is specifically not designed for compatibility with the existing HTTP/1 module API. However, the Compatibility API is.
The http2 Core API is much more symmetric between client and server than the
http API. For instance, most events, like 'error', 'connect' and
'stream', can be emitted either by client-side code or server-side code.
Server-side example#
The following illustrates a simple HTTP/2 server using the Core API.
Since there are no browsers known that support
unencrypted HTTP/2, the use of
http2.createSecureServer() is necessary when communicating
with browser clients.
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; charset=utf-8',
':status': 200
});
stream.end('<h1>Hello World</h1>');
});
server.listen(8443);
To generate the certificate and key for this example, run:
openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
-keyout localhost-privkey.pem -out localhost-cert.pem
Client-side example#
The following illustrates an HTTP/2 client:
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();
Class: Http2Session#
- Extends: <EventEmitter>
Instances of the http2.Http2Session class represent an active communications
session between an HTTP/2 client and server. Instances of this class are not
intended to be constructed directly by user code.
Each Http2Session instance will exhibit slightly different behaviors
depending on whether it is operating as a server or a client. The
http2session.type property can be used to determine the mode in which an
Http2Session is operating. On the server side, user code should rarely
have occasion to work with the Http2Session object directly, with most
actions typically taken through interactions with either the Http2Server or
Http2Stream objects.
User code will not create Http2Session instances directly. Server-side
Http2Session instances are created by the Http2Server instance when a
new HTTP/2 connection is received. Client-side Http2Session instances are
created using the http2.connect() method.
Http2Session and sockets#
Every Http2Session instance is associated with exactly one net.Socket or
tls.TLSSocket when it is created. When either the Socket or the
Http2Session are destroyed, both will be destroyed.
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 Socket instance bound to a Http2Session. Doing so can
put the HTTP/2 session into an indeterminate state causing the session and
the socket to become unusable.
Once a Socket has been bound to an Http2Session, user code should rely
solely on the API of the Http2Session.
Event: 'close'#
The 'close' event is emitted once the Http2Session has been destroyed. Its
listener does not expect any arguments.
Event: 'connect'#
session<Http2Session>socket<net.Socket>
The 'connect' event is emitted once the Http2Session has been successfully
connected to the remote peer and communication may begin.
User code will typically not listen for this event directly.
Event: 'error'#
error<Error>
The 'error' event is emitted when an error occurs during the processing of
an Http2Session.
Event: 'frameError'#
type<integer> The frame type.code<integer> The error code.id<integer> The stream id (or0if the frame isn't associated with a stream).
The 'frameError' 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 Http2Stream, an attempt to emit a 'frameError' event on the
Http2Stream is made.
If the 'frameError' event is associated with a stream, the stream will be
closed and destroyed immediately following the 'frameError' event. If the
event is not associated with a stream, the Http2Session will be shut down
immediately following the 'frameError' event.
Event: 'goaway'#
errorCode<number> The HTTP/2 error code specified in theGOAWAYframe.lastStreamID<number> The ID of the last stream the remote peer successfully processed (or0if no ID is specified).opaqueData<Buffer> If additional opaque data was included in theGOAWAYframe, aBufferinstance will be passed containing that data.
The 'goaway' event is emitted when a GOAWAY frame is received.
The Http2Session instance will be shut down automatically when the 'goaway'
event is emitted.
Event: 'localSettings'#
settings<HTTP/2 Settings Object> A copy of theSETTINGSframe received.
The 'localSettings' event is emitted when an acknowledgment SETTINGS frame
has been received.
When using http2session.settings() to submit new settings, the modified
settings do not take effect until the 'localSettings' event is emitted.
session.settings({ enablePush: false });
session.on('localSettings', (settings) => {
/* Use the new settings */
});
Event: 'ping'#
payload<Buffer> ThePINGframe 8-byte payload
The 'ping' event is emitted whenever a PING frame is received from the
connected peer.
Event: 'remoteSettings'#
settings<HTTP/2 Settings Object> A copy of theSETTINGSframe received.
The 'remoteSettings' event is emitted when a new SETTINGS frame is received
from the connected peer.
session.on('remoteSettings', (settings) => {
/* Use the new settings */
});
Event: 'stream'#
stream<Http2Stream> A reference to the streamheaders<HTTP/2 Headers Object> An object describing the headersflags<number> The associated numeric flagsrawHeaders<Array> An array containing the raw header names followed by their respective values.
The 'stream' event is emitted when a new Http2Stream is created.
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; charset=utf-8'
});
stream.write('hello ');
stream.end('world');
});
On the server side, user code will typically not listen for this event directly,
and would instead register a handler for the 'stream' event emitted by the
net.Server or tls.Server instances returned by http2.createServer() and
http2.createSecureServer(), respectively, as in the example below:
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; charset=utf-8',
':status': 200
});
stream.on('error', (error) => console.error(error));
stream.end('<h1>Hello World</h1>');
});
server.listen(80);
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.
Event: 'timeout'#
After the http2session.setTimeout() method is used to set the timeout period
for this Http2Session, the 'timeout' event is emitted if there is no
activity on the Http2Session after the configured number of milliseconds.
Its listener does not expect any arguments.
session.setTimeout(2000);
session.on('timeout', () => { /* .. */ });