http2 module in Node.js
The http2
module in Node.js provides an implementation of the HTTP/2 protocol, which is a major revision of the HTTP protocol designed to improve performance and efficiency. Here’s an overview of the http2
module, its features, and how it differs from the http
module:
Key Features of the http2
Module
- Multiplexing: Multiple requests and responses can be sent over a single TCP connection simultaneously, reducing latency and improving performance.
- Header Compression: Uses HPACK header compression to reduce the overhead of HTTP headers.
- Server Push: Allows the server to send resources to the client proactively, without the client having to request them.
- Binary Protocol: HTTP/2 uses a binary framing layer, which is more efficient than the text-based HTTP/1.x protocols.
Creating an HTTP/2 Server
Basic Example
Here’s a simple example of creating an HTTP/2 server:
const http2 = require('http2');
const fs = require('fs');
const path = require('path');
const server = http2.createSecureServer({
key: fs.readFileSync(path.join(__dirname, 'key.pem')),
cert: fs.readFileSync(path.join(__dirname, 'cert.pem'))
});
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html',
':status': 200
});
stream.end('<h1>Hello, HTTP/2!</h1>');
});
server.listen(8443, () => {
console.log('HTTP/2 server running on port 8443');
});
Server Push Example
Here’s how you can implement server push with HTTP/2:
const http2 = require('http2');
const fs = require('fs');
const path = require('path');
const server = http2.createSecureServer({
key: fs.readFileSync(path.join(__dirname, 'key.pem')),
cert: fs.readFileSync(path.join(__dirname, 'cert.pem'))
});
server.on('stream', (stream, headers) => {
if (headers[':path'] === '/') {
stream.pushStream({ ':path': '/style.css' }, (err, pushStream) => {
if (err) throw err;
pushStream.respond({ ':status': 200 });
pushStream.end('body { background: #0f0; }');
});
stream.respond({ ':status': 200, 'content-type': 'text/html' });
stream.end('<link rel="stylesheet" href="style.css"><h1>Hello, HTTP/2 with Server Push!</h1>');
}
});
server.listen(8443, () => {
console.log('HTTP/2 server running on port 8443');
});
Creating an HTTP/2 Client
Here’s an example of an HTTP/2 client making a request:
const http2 = require('http2');
const client = http2.connect('https://localhost:8443', {
ca: fs.readFileSync(path.join(__dirname, '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');
req.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
req.on('end', () => {
console.log('No more data in response.');
client.close();
});
req.end();
Differences Between http2
and http
Modules
-
Protocol Version:
http
: Implements HTTP/1.0 and HTTP/1.1.http2
: Implements HTTP/2.
-
Connection Multiplexing:
http
: Each request/response pair requires a new TCP connection unless keep-alive is used.http2
: Multiple requests and responses can be multiplexed over a single TCP connection.
-
Header Compression:
http
: Headers are sent as plain text, with potential redundancy.http2
: Uses HPACK compression to reduce the size of headers.
-
Server Push:
http
: No native support for server push.http2
: Supports server push, allowing the server to send resources to the client before they are requested.
-
Binary Protocol:
http
: Uses a text-based protocol.http2
: Uses a binary protocol, which is more efficient in terms of parsing and handling.
-
API Differences:
http
: The API is based on the traditional request/response model.http2
: The API introduces the concept of streams and sessions, allowing for more advanced use cases like server push and multiplexing.
Practical Applications
- Improved Performance: HTTP/2 can significantly reduce latency and improve the performance of web applications by leveraging multiplexing and header compression.
- Modern Web Applications: Utilize server push to proactively send resources to the client, reducing the need for additional requests.
- Efficient Network Utilization: Make better use of available bandwidth by sending multiple requests and responses over a single connection.
Published on: Jun 19, 2024, 02:56 AM