http2-wrapper
HTTP2 client, just with the familiar https
API
This package was created to support HTTP2 without the need to rewrite your code.
I recommend adapting to the http2
module if possible - it's much simpler to use and has many cool features!
Tip: http2-wrapper
is very useful when you rely on other modules that use the HTTP1 API and you want to support HTTP2.
Installation
$ npm install http2-wrapper
$ yarn add http2-wrapper
It's best to run http2-wrapper
under the latest version of Node. It provides the best stability.
Usage
const http2 = require('http2-wrapper');
const options = {
hostname: 'nghttp2.org',
protocol: 'https:',
path: '/httpbin/post',
method: 'POST',
headers: {
'content-length': 6
}
};
const request = http2.request(options, response => {
console.log('statusCode:', response.statusCode);
console.log('headers:', response.headers);
const body = [];
response.on('data', chunk => {
body.push(chunk);
});
response.on('end', () => {
console.log('body:', Buffer.concat(body).toString());
});
});
request.on('error', e => console.error(e));
request.write('123');
request.end('456');
API
Note: the session
option accepts an instance of Http2Session
. To pass a TLS session, use tlsSession
instead.
http2.auto(url, options, callback)
Performs ALPN negotiation.
Returns a Promise giving proper ClientRequest
instance (depending on the ALPN).
Tip: the agent
option also accepts an object with http
, https
and http2
properties.
const http2 = require('http2-wrapper');
const options = {
hostname: 'httpbin.org',
protocol: 'http:',
path: '/post',
method: 'POST',
headers: {
'content-length': 6
}
};
(async () => {
try {
const request = await http2.auto(options, response => {
console.log('statusCode:', response.statusCode);
console.log('headers:', response.headers);
const body = [];
response.on('data', chunk => body.push(chunk));
response.on('end', () => {
console.log('body:', Buffer.concat(body).toString());
});
});
request.on('error', console.error);
request.write('123');
request.end('456');
} catch (error) {
console.error(error);
}
})();
http2.auto.prepareRequest(options)
Performs ALPN negotiation.
Returns a Promise giving proper request function depending on the ALPN protocol.
Note: the request function takes only two arguments: options
and callback
.
Tip: the agent
option also accepts an object with http
, https
and http2
properties.
http2.auto.resolveALPN(options)
Returns a Promise giving the best ALPN protocol possible. It can be either h2
or http/1.1
.
http2.auto.protocolCache
An instance of quick-lru
used for ALPN cache.
There is a maximum of 100 entries. You can modify the limit through protocolCache.maxSize
- note that the change will be visible globally.
http2.request(url, options, callback)
Same as https.request
.
options.preconnect
Type: boolean
Default: true
If set to true
, it will try to connect to the server before sending the request.
http2.get(url, options, callback)
Same as https.get
.
new http2.ClientRequest(url, options, callback)
Same as https.ClientRequest
.
new http2.IncomingMessage(socket)
Same as https.IncomingMessage
.
new http2.Agent(options)
Note: this is not compatible with the classic http.Agent
.
Usage example:
const http2 = require('http2-wrapper');
class MyAgent extends http2.Agent {
createConnection(authority, options) {
console.log(`Connecting to ${authority}`);
return http2.Agent.connect(authority, options);
}
}
http2.get({
hostname: 'google.com',
agent: new MyAgent()
}, res => {
res.on('data', chunk => console.log(`Received chunk of ${chunk.length} bytes`));
});
options
Each option is assigned to each Agent
instance and can be changed later.
timeout
Type: number
Default: 60000
If there's no activity after timeout
milliseconds, the session will be closed.
maxSessions
Type: number
Default: Infinity
The maximum amount of sessions per origin.
maxFreeSessions
Type: number
Default: 1
The maximum amount of free sessions per origin.
maxCachedTlsSessions
Type: number
Default: 100
The maximum amount of cached TLS sessions.
Agent.normalizeAuthority(authority, servername)
Normalizes the authority URL.
Agent.normalizeAuthority('https://example.com:443');
Agent.normalizeOptions(options)
Returns a string containing normalized options.
Agent.normalizeOptions({servername: 'example.com'});
agent.settings
Type: object
Default: {enablePush: false}
Settings used by the current agent instance.
agent.getSession(authority, options)
Type: string
URL
object
Authority used to create a new session.
Type: object
Options used to create a new session.
Returns a Promise giving free Http2Session
. If no free sessions are found, a new one is created.
listener
Type: object
{
reject: error => void,
resolve: session => void
}
If the listener
argument is present, the Promise will resolve immediately. It will use the resolve
function to pass the session.
Returns a Promise giving Http2Stream
.
Returns a new TLSSocket
. It defaults to Agent.connect(authority, options)
.
agent.closeFreeSessions()
Makes an attempt to close free sessions. Only sessions with 0 concurrent streams are closed.
agent.destroy(reason)
Destroys all sessions.
Notes
Benchmarks
CPU: Intel i7-7700k
Server: H2O 2.2.5 h2o.conf
Node: v12.10.0
http2-wrapper x 9,954 ops/sec ±3.72% (81 runs sampled)
http2-wrapper - preconfigured session x 12,309 ops/sec ±1.48% (87 runs sampled)
http2 x 14,664 ops/sec ±1.63% (78 runs sampled)
http2 - using PassThrough proxies x 11,884 ops/sec ±2.43% (82 runs sampled)
https x 1,586 ops/sec ±4.05% (79 runs sampled)
http x 5,886 ops/sec ±2.73% (76 runs sampled)
Fastest is http2
http2-wrapper
:
- It's
1.473x
slower than http2
. - It's
1.194x
slower than http2
with 2xPassThrough
. - It's
6.276x
faster than https
. - It's
1.691x
faster than http
.
http2-wrapper - preconfigured session
:
- It's
1.191x
slower than http2
. - It's
1.036x
faster than http2
with 2xPassThrough
. - It's
7.761x
faster than https
. - It's
2.091x
faster than http
.
Related
got
- Simplified HTTP requests
License
MIT