Home

Awesome

Router

A high-performance basic router works anywhere.

tag Build Status license

Features

Usage

Deno

See zhmushan/abc

Nodejs

Installation:

npm i zhmushan/router#v2

Create index.js:

// import * as http from "http";
// import { Node } from "router";

const http = require("http");
const Node = require("router").Node;

const root = new Node();

root.add("/:user", (p) => {
  return p.get("user");
});

http.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");

Run:

node index.js

Browse to http://localhost:8080/your_name and you should see "your_name" on the page.

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@v2.0.1/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>