GPT o1都告诉不了你的Nodejs搭建H2兼容http1.1服务器方式,npm包推荐

这块领域网上资料少,GPT和Claude的回答都不能直接完成.不过通过它们提供的一些思路加上搜索资料,还是让我拼凑了出来,顺便推荐一个自用的高效npm库:
拿创建HTTP2 TLS服务器举例,原本复杂的路径处理:

import http2 from "http2";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const server = http2.createSecureServer({
  key: fs.readFileSync(path.join(__dirname, "cert/key.pem")),
  cert: fs.readFileSync(path.join(__dirname, "cert/cert.pem")),
  allowHTTP1: true,
});

可简化为:
npm i @ghini/kit-dev

import http2 from "http2";
import { autopath,rf } from "@ghini/kit-dev";

const server = http2.createSecureServer({
  key: rf(autopath("cert/key.pem")),
  cert: rf(autopath("cert/cert.pem")),
  allowHTTP1: true,
});

补全后面代码供测试,一个基础的h2兼容h1.1的nodejs服务器:

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`HTTP/2 服务器运行在 https://localhost:${PORT}`);
});
server.on("stream", (stream, headers, flags, rawHeaders) => {
  stream.respond({
    "content-type": "text/html; charset=utf-8",
    ":status": 200,
  });
  stream.end('Hello, H2!');
});
// 处理 HTTP/1.1 请求
server.on("request", (req, res) => {
  if(req.headers[":path"])return;
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello, HTTP/1.1!");
});

image
image

10 Likes

太强了,佬:+1:

不懂就问,这个有哪些妙用

感谢你的分享。

感谢你的分享。