HTTP маршрутизатор для Node.js на основе префиксного дерева
|
|
1 year ago | |
|---|---|---|
| .husky | 1 year ago | |
| examples | 1 year ago | |
| src | 1 year ago | |
| .c8rc | 1 year ago | |
| .commitlintrc | 1 year ago | |
| .editorconfig | 1 year ago | |
| .gitignore | 1 year ago | |
| .mocharc.cjs | 1 year ago | |
| .prettierrc | 1 year ago | |
| LICENSE | 1 year ago | |
| README.md | 1 year ago | |
| eslint.config.js | 1 year ago | |
| package.json | 1 year ago | |
| tsconfig.json | 1 year ago |
A pure ES-module of the Node.js HTTP router that uses the Trie for routing.
preHandler and postHandler
hooks.npm install @e22m4u/js-trie-router
A basic "Hello world." example.
import http from 'http';
import {TrieRouter} from '../src/index.js';
import {HTTP_METHOD} from '../src/route.js';
const server = new http.Server(); // A Node.js HTTP server.
const router = new TrieRouter(); // A TrieRouter instance.
router.defineRoute({
method: HTTP_METHOD.GET, // Request method.
path: '/', // Path template like "/user/:id".
handler(ctx) { // Request handler.
return 'Hello world!';
},
});
server.on('request', router.requestHandler);
server.listen(3000, 'localhost');
// Open in browser http://localhost:3000
The first parameter of the Router handler is the
RequestContext instance.
container: ServiceContainerreq: IncomingMessageres: ServerResponsequery: ParsedQueryheaders: ParsedHeaderscookie: ParsedCookieThe RequestContext can be destructured.
router.defineRoute({
// ...
handler({req, res, query, headers, cookie}) {
console.log(req); // IncomingMessage
console.log(res); // ServerResponse
console.log(query); // {id: '10', ...}
console.log(headers); // {'cookie': 'foo=bar', ...}
console.log(cookie); // {foo: 'bar', ...}
// ...
},
});
Return values of the Route handler will be sent as
described below.
| type | content-type |
|---|---|
string |
text/plain |
number |
application/json |
boolean |
application/json |
object |
application/json |
Buffer |
application/octet-stream |
Stream |
application/octet-stream |
Here is an example of a JSON response.
router.defineRoute({
// ...
handler(ctx) {
// sends "application/json"
return {foo: 'bar'};
},
});
If the ServerResponse has been sent manually, then the
return value will be ignored.
router.defineRoute({
// ...
handler(ctx) {
res.statusCode = 404;
res.setHeader('content-type', 'text/plain; charset=utf-8');
res.end('404 Not Found', 'utf-8');
},
});
Set environment variable DEBUG=jsTrieRouter* before
start.
DEBUG=jsPathTrie* npm run test
npm run test
MIT