444530
先放链接:https://github.com/vincent178/flexrouter
为什么重新发明一个路由轮子?
react-router vue-router express 还有koa 都是用的 path-to-regexp, 将路由转化成正则表达式,然后循环比对当前路径找到符合的路由。在大量路由情况下查找性能会比较差。 Go 有个高性能的http路由 https://github.com/julienschmidt/httprouter, 内部使用 Radix Tree 实现高性能路由查找,我也撸了一个 ts 版本的。
特性
支持前端和后端:
后端例子没有用任何node框架 http 路由 https://github.com/vincent178/flexrouter/tree/master/examples/http-server-with-flexrouter 前端例子是 react 页面路由 https://github.com/vincent178/flexrouter/tree/master/examples/react-router-with-flexrouter
高性能:
在2000+路由的情况下,benchmark数据
path-to-regexp#home x 4,247 ops/sec ±1.82% (83 runs sampled)
flexrouter#home x 4,856,189 ops/sec ±0.71% (88 runs sampled)
path-to-regexp#topic-detail x 4,247 ops/sec ±1.33% (86 runs sampled)
flexrouter#topic-detail x 1,254,182 ops/sec ±0.82% (88 runs sampled)
多种格式支持:
static route: /home
param route: /topic/:id
param route with regex: topic/photo-:id(/\\d+/).jpg
wildcard route: /*site
其他细节 https://github.com/vincent178/flexrouter
fastify也有个类似的实现叫 find-my-way, 但是它实现有点问题,这也是我想自己实现一个版本的原因。