Node.js 中的 http2 模块的使用

发布于:2025-03-12 ⋅ 阅读:(16) ⋅ 点赞:(0)
概念

http2 是 Node.js 中的一个核心模块,用于实现 HTTP/2 协议。HTTP/2 是 HTTP/1.1 的升级版本,旨在提高 Web 性能。它引入了多路复用、头部压缩、服务器推送等特性,显著减少了延迟并提高了数据传输效率。

意义
  1. 性能提升:HTTP/2 通过多路复用允许在同一个连接上并行发送多个请求和响应,减少了连接建立的开销。
  2. 头部压缩:使用 HPACK 算法压缩头部信息,减少了数据传输量。
  3. 服务器推送:服务器可以在客户端请求之前主动推送资源,减少延迟。
  4. 二进制协议:HTTP/2 使用二进制格式传输数据,解析效率更高。
优缺点

优点

  • 减少延迟,提高页面加载速度。
  • 更高效的资源利用,减少带宽消耗。
  • 支持服务器推送,优化用户体验。

缺点

  • 需要 HTTPS 加密,增加了服务器配置的复杂性。
  • 对旧版浏览器的兼容性较差。
使用示例

以下是一个简单的 HTTP/2 服务器和客户端的实现示例。

1. 创建 HTTP/2 服务器
const http2 = require('http2');
const fs = require('fs');

// 读取 SSL 证书和密钥
const options = {
  key: fs.readFileSync('localhost-privkey.pem'),
  cert: fs.readFileSync('localhost-cert.pem')
};

// 创建 HTTP/2 服务器
const server = http2.createSecureServer(options, (req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, HTTP/2!');
});

// 监听端口
server.listen(8443, () => {
  console.log('HTTP/2 server is listening on https://localhost:8443');
});
2. 创建 HTTP/2 客户端
const http2 = require('http2');

// 创建 HTTP/2 客户端
const client = http2.connect('https://localhost:8443', {
  ca: fs.readFileSync('localhost-cert.pem') // 使用自签名证书时需要提供 CA
});

// 创建请求
const req = client.request({ ':path': '/' });

// 接收响应数据
req.on('response', (headers) => {
  console.log('Response headers:', headers);
});

let data = '';
req.on('data', (chunk) => {
  data += chunk;
});

req.on('end', () => {
  console.log('Response body:', data);
  client.close();
});

req.end();
3. 服务器推送示例
const http2 = require('http2');
const fs = require('fs');

const options = {
  key: fs.readFileSync('localhost-privkey.pem'),
  cert: fs.readFileSync('localhost-cert.pem')
};

const server = http2.createSecureServer(options, (req, res) => {
  if (req.url === '/') {
    // 推送额外的资源
    res.stream.pushStream({ ':path': '/style.css' }, (err, pushStream) => {
      if (err) throw err;
      pushStream.respond({ ':status': 200 });
      pushStream.end('body { background-color: yellow; }');
    });

    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('<link rel="stylesheet" href="/style.css"><h1>Hello, HTTP/2 with Push!</h1>');
  }
});

server.listen(8443, () => {
  console.log('HTTP/2 server with push is listening on https://localhost:8443');
});
总结

Node.js 的 http2 模块为开发者提供了实现 HTTP/2 协议的能力,显著提升了 Web 应用的性能。通过多路复用、头部压缩和服务器推送等特性,HTTP/2 能够有效减少延迟和带宽消耗。然而,使用 HTTP/2 需要配置 HTTPS,且对旧版浏览器的支持有限。通过上述示例,开发者可以快速上手并利用 http2 模块构建高效的 Web 应用。