Security News
The Unpaid Backbone of Open Source: Solo Maintainers Face Increasing Security Demands
Solo open source maintainers face burnout and security challenges, with 60% unpaid and 60% considering quitting.
http2-wrapper
Advanced tools
The http2-wrapper npm package is a module that provides an easy-to-use wrapper around the native HTTP/2 client and server capabilities in Node.js. It simplifies the process of making HTTP/2 requests and handling responses, as well as creating HTTP/2 servers.
Making HTTP/2 requests
This feature allows you to make HTTP/2 requests to a server. The code sample demonstrates how to perform a simple GET request using the http2-wrapper.
const http2wrapper = require('http2-wrapper');
const options = {
hostname: 'example.com',
protocol: 'https:',
path: '/',
method: 'GET'
};
http2wrapper.request(options, (res) => {
console.log(`Status Code: ${res.statusCode}`);
res.on('data', (chunk) => {
console.log(chunk);
});
}).end();
Creating HTTP/2 servers
This feature allows you to create an HTTP/2 server. The code sample shows how to set up a simple HTTP/2 server that responds with 'Hello World' to all requests.
const http2wrapper = require('http2-wrapper');
const http2 = require('http2');
const server = http2.createSecureServer({
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem')
});
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html',
':status': 200
});
stream.end('<h1>Hello World</h1>');
});
http2wrapper.createServer(server).listen(8443);
The 'spdy' package is an HTTP/2 and SPDY protocol client and server implementation for Node.js. It provides similar functionalities to http2-wrapper but also includes support for SPDY, which is a now-deprecated protocol that was a precursor to HTTP/2.
While 'node-fetch' is primarily a light-weight module that brings window.fetch to Node.js, it can be used to make HTTP/2 requests when combined with the built-in http2 module in Node.js. It does not provide server capabilities like 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.
$ 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.
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');
// statusCode: 200
// headers: [Object: null prototype] {
// ':status': 200,
// date: 'Fri, 27 Sep 2019 19:45:46 GMT',
// 'content-type': 'application/json',
// 'access-control-allow-origin': '*',
// 'access-control-allow-credentials': 'true',
// 'content-length': '239',
// 'x-backend-header-rtt': '0.002516',
// 'strict-transport-security': 'max-age=31536000',
// server: 'nghttpx',
// via: '1.1 nghttpx',
// 'alt-svc': 'h3-23=":4433"; ma=3600',
// 'x-frame-options': 'SAMEORIGIN',
// 'x-xss-protection': '1; mode=block',
// 'x-content-type-options': 'nosniff'
// }
// body: {
// "args": {},
// "data": "123456",
// "files": {},
// "form": {},
// "headers": {
// "Content-Length": "6",
// "Host": "nghttp2.org"
// },
// "json": 123456,
// "origin": "xxx.xxx.xxx.xxx",
// "url": "https://nghttp2.org/httpbin/post"
// }
Note: the session
option accepts an instance of Http2Session
. To pass a TLS session, use tlsSession
instead.
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:', // Note the `http:` protocol here
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);
}
})();
// statusCode: 200
// headers: { connection: 'close',
// server: 'gunicorn/19.9.0',
// date: 'Sat, 15 Dec 2018 18:19:32 GMT',
// 'content-type': 'application/json',
// 'content-length': '259',
// 'access-control-allow-origin': '*',
// 'access-control-allow-credentials': 'true',
// via: '1.1 vegur' }
// body: {
// "args": {},
// "data": "123456",
// "files": {},
// "form": {},
// "headers": {
// "Connection": "close",
// "Content-Length": "6",
// "Host": "httpbin.org"
// },
// "json": 123456,
// "origin": "xxx.xxx.xxx.xxx",
// "url": "http://httpbin.org/post"
// }
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.
Returns a Promise giving the best ALPN protocol possible. It can be either h2
or http/1.1
.
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.
Same as https.request
.
Type: boolean
Default: true
If set to true
, it will try to connect to the server before sending the request.
Same as https.get
.
Same as https.ClientRequest
.
Same as https.IncomingMessage
.
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`));
});
Each option is assigned to each Agent
instance and can be changed later.
Type: number
Default: 60000
If there's no activity after timeout
milliseconds, the session will be closed.
Type: number
Default: Infinity
The maximum amount of sessions per origin.
Type: number
Default: 1
The maximum amount of free sessions per origin.
Type: number
Default: 100
The maximum amount of cached TLS sessions.
Normalizes the authority URL.
Agent.normalizeAuthority('https://example.com:443');
// => 'https://example.com'
Returns a string containing normalized options.
Agent.normalizeOptions({servername: 'example.com'});
// => ':example.com'
Type: object
Default: {enablePush: false}
Settings used by the current agent instance.
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.
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)
.
Makes an attempt to close free sessions. Only sessions with 0 concurrent streams are closed.
Destroys all sessions.
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
:
1.473x
slower than http2
.1.194x
slower than http2
with 2xPassThrough
.6.276x
faster than https
.1.691x
faster than http
.http2-wrapper - preconfigured session
:
1.191x
slower than http2
.1.036x
faster than http2
with 2xPassThrough
.7.761x
faster than https
.2.091x
faster than http
.got
- Simplified HTTP requestsMIT
FAQs
HTTP2 client, just with the familiar `https` API
The npm package http2-wrapper receives a total of 10,481,186 weekly downloads. As such, http2-wrapper popularity was classified as popular.
We found that http2-wrapper demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Solo open source maintainers face burnout and security challenges, with 60% unpaid and 60% considering quitting.
Security News
License exceptions modify the terms of open source licenses, impacting how software can be used, modified, and distributed. Developers should be aware of the legal implications of these exceptions.
Security News
A developer is accusing Tencent of violating the GPL by modifying a Python utility and changing its license to BSD, highlighting the importance of copyleft compliance.