高性能的 Router, 可以同时在 Deno, Nodejs, Browser 中使用
发布于 6 年前 作者 zhmushan 4280 次浏览 来自 分享

项目链接

特征

  • 基于 radix tree : 与基于正则表达式的路由器相比,在大多数情况下,我们都有更好的性能,这可以显着提高项目速度,并且随着项目规模的增加,性能也将成倍增加。

  • 愚蠢的规则: 我们将始终根据 "Static > Param > Any" 的规则进行匹配。对于 Static 路由,我们始终匹配严格相等的字符串。

用法

Deno

参考 zhmushan/abc

Nodejs

安装:

npm i zhmushan/router#v1.0.0

创建 index.js:

import { createServer } from "http";
import { Node } from "router";
const root = new Node();
root.add("/:user", (p) => {
 return p.get("user");
});
createServer((req, res) => {
 const [h, p] = root.find(req.url);
 if (h) {
 const result = h(p);
 res.end(result);
 } else {
 res.end("Not Found");
 }
}).listen(8080);
console.log("server listening on http://localhost:8080");

确保已在 package.json 中设置 type: module,然后执行:

node index.js

打开 http://localhost:8080/your_name ,你应该在页面上看到 "your_name"。

Browser

<body>
 <button id="change_path">Change Path</button>
 <button id="home">Home</button>
 <script type="module">
 import { Node } from "https://deno.land/x/router@v1.0.0/mod.js";
 const root = new Node();
 root.add("/:random_string", (c) => {
 console.log(c.get("random_string"));
 });
 change_path.onclick = () => {
 const path = `/${randomStr()}`;
 const [func, params] = root.find(path);
 if (func) {
 func(params);
 history.replaceState(undefined, "", path);
 }
 };
 home.onclick = () => {
 history.replaceState(undefined, "", "/");
 };
 function randomStr() {
 return Math.random().toString(32).split(".")[1];
 }
 </script>
</body>
1 回复
回到顶部

AltStyle によって変換されたページ (->オリジナル) /