What is http2-wrapper?
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.
What are http2-wrapper's main functionalities?
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);
Other packages similar to http2-wrapper
spdy
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.
node-fetch
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-wrapper
Use HTTP2 the same way like HTTP1
Usage
'use strict';
const http2 = require('.');
const options = {
hostname: 'nghttp2.org',
protocol: 'https:',
path: '/httpbin/post',
method: 'POST',
headers: {
'content-length': 6
}
};
const req = http2.request(options, res => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
const body = [];
res.on('data', chunk => {
body.push(chunk);
});
res.on('end', () => {
console.log('body:', Buffer.concat(body).toString());
});
});
req.on('error', e => console.error(e));
req.write('123');
req.end('456');
TODO
HTTP2IncomingMessage
HTTP2ClientRequest