有研究可能会发现,用express,fastify,koa对H2支持都不够(挺麻烦,对比就知道),加中间件,效果还不怎么好.
本人热爱JS这门语言,所以基于原生模块http2,精心开发填补这片空缺.
直接看使用示例(h2浏览器直接访问;h1用nginx反代或postman默认,axios node-fetch以及很多后端curl默认都是)
npm i @ghini/kit-dev
核心函数 h2s(port,[config,handle])
import {h2s} from "@ghini/kit-dev";
h2s(3000)
默认绑定3000端口,配置了自签名证书,开启http1兼容
但还是推荐写上端口号(配置config或handle必写)
稍做修改,写函数handleStream处理路由
import {h2s,xconsole} from "@ghini/kit-dev";
h2s(3000, handleStream);
function handleStream(stream, headers) {
const path=headers[":path"]
if(path==="/"){
stream.respond({
":status": 200,
"content-type": "application/json",
});
stream.write(JSON.stringify(headers));
stream.end();
}
else if(path==="/hello") {
stream.end("Hello World!")
}
}
xconsole,加强console.log和console.error输出,多出[时间|行号|色彩]
一次性开启多个也是没有任何问题,第五个让端口重复看错误处理
import {h2s,xconsole,rf,xpath} from "@ghini/kit-dev";
xconsole()
h2s(3001);
h2s(3002, handleStream);
h2s(3003, { allowHTTP1: false });
h2s(3004, { allowHTTP1: false }, handleStream);
h2s(3004, {
key: rf(xpath("cert/selfsigned.key")),
cert: rf(xpath("cert/selfsigned.cert")),
allowHTTP1: false,
...{}
}, handleStream);
function handleStream(stream, headers) {
const path=headers[":path"]
if(path==="/"){
stream.respond({
":status": 200,
"content-type": "application/json",
});
stream.write(JSON.stringify(headers));
stream.end();
}
else if(path==="/hello") {
stream.end("Hello World!")
}
}
就不一访问了,可以自行尝试
新导入的rf和xpath也是实用函数,有兴趣可以看源码研究
Github : GitHub - xghini/node-kit: JS高效泛功能库