packeteer
v1.0.1
Published
Minimal HTTP server for Node.js with trie-based routing and built-in JSON body parsing.
Downloads
11
Readme
packeteer
Minimal HTTP server for Node.js with trie-based routing and built-in JSON body parsing.
Install
npm install packeteerUsage
import { Packeteer } from 'packeteer'
const app = await new Packeteer()
.get('/health', (_req, res, _ctx) => {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'ok' }))
})
.post('/echo', (_req, res, ctx) => {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(ctx.get('body')))
})
.listen(3000)
console.log(app.address())API
new Packeteer()
Creates a new server instance. CORS headers (Access-Control-Allow-*: *) are set on every response automatically.
.get(path, handler) / .post / .put / .delete / .patch
Registers a route. Returns this for chaining.
The handler signature is:
(request: IncomingMessage, response: ServerResponse, context: Map<string, unknown>) => Promise<void> | voidcontext contains body (parsed JSON) when the request has a body.
Path parameters
Prefix a segment with : to capture it by name:
app.get('/users/:id', (_req, res, ctx) => {
res.end(ctx.get('id') as string) // e.g. "42" for /users/42
})Wildcards
End a path with * to capture all remaining segments as a single slash-joined string under the key 'wildcard':
app.get('/files/*', (_req, res, ctx) => {
res.end(ctx.get('wildcard') as string) // e.g. "images/avatar.png" for /files/images/avatar.png
}).maxBodySize(bytes)
Overrides the default 8 MB body size limit. Returns this for chaining.
new Packeteer().maxBodySize(1024 * 1024) // 1 MB.listen(port): Promise<this>
Starts the server and resolves when it is ready.
.address()
Returns the bound address (delegates to server.address()).
.close(): Promise<void>
Stops the server.
Behaviour
- JSON bodies are parsed automatically and available as
ctx.get('body'). - Bodies over the size limit (default 8 MB) are rejected with
413. - Malformed JSON is rejected with
400. TypeError/RangeErrorthrown from a handler return400with the error message.- Any other thrown error returns
500and is logged to stderr. - Unmatched routes return
404.
Requirements
Node.js 18 or later.
