What is trouter?
Trouter is a lightweight and fast router for Node.js that allows you to define routes and handle HTTP requests. It is designed to be minimalistic and efficient, making it suitable for building small to medium-sized web applications and APIs.
What are trouter's main functionalities?
Basic Routing
This feature allows you to define basic routes for handling HTTP GET requests. The code sample demonstrates how to create a simple route that responds with 'Hello, world!' when accessed.
const Trouter = require('trouter');
const router = new Trouter();
router.get('/hello', (req, res) => {
res.end('Hello, world!');
});
// Simulate a request
const req = { method: 'GET', url: '/hello' };
const res = { end: console.log };
router.find(req.method, req.url).handlers[0](req, res);
Route Parameters
This feature allows you to define routes with parameters. The code sample demonstrates how to create a route that captures a user ID from the URL and responds with the user ID.
const Trouter = require('trouter');
const router = new Trouter();
router.get('/user/:id', (req, res) => {
const { id } = req.params;
res.end(`User ID: ${id}`);
});
// Simulate a request
const req = { method: 'GET', url: '/user/123', params: { id: '123' } };
const res = { end: console.log };
router.find(req.method, req.url).handlers[0](req, res);
Middleware Support
This feature allows you to use middleware functions in your routes. The code sample demonstrates how to create a logger middleware that logs the request method and URL before handling the request.
const Trouter = require('trouter');
const router = new Trouter();
const logger = (req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
};
router.use(logger);
router.get('/hello', (req, res) => {
res.end('Hello, world!');
});
// Simulate a request
const req = { method: 'GET', url: '/hello' };
const res = { end: console.log };
const { handlers } = router.find(req.method, req.url);
handlers[0](req, res, () => handlers[1](req, res));
Other packages similar to trouter
express
Express is a widely-used web application framework for Node.js. It provides robust routing capabilities, middleware support, and a wide range of features for building web applications and APIs. Compared to Trouter, Express is more feature-rich and suitable for larger applications.
koa
Koa is a web framework designed by the team behind Express. It aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. Koa uses async functions for middleware, providing a more modern approach compared to Trouter.
hapi
Hapi is a rich framework for building applications and services. It is known for its powerful plugin system and configuration-driven approach. Hapi offers more built-in features and flexibility compared to Trouter, making it suitable for complex applications.
trouter
🐟 A fast, small-but-mighty, familiar fish router
Install
$ npm install --save trouter
Usage
import Trouter from 'trouter';
const router = new Trouter();
router
.get('/users', _ => {
console.log('> Getting all users');
})
.add('POST', '/users', _ => {
console.log('~> Adding a user');
})
.get('/users/:id', val => {
console.log('~> Getting user with ID:', val);
});
let obj = router.find('GET', '/users/123');
obj.handlers.forEach(fn => {
fn(obj.params.id);
});
router.find('DELETE', '/foo');
API
Trouter()
Initializes a new Trouter
instance.
trouter.add(method, pattern, ...handlers)
Returns: self
Stores a method
+ pattern
pairing internally, along with its handler(s).
method
Type: String
Any uppercased, valid HTTP/1.1 verb — choose from one of the following:
GET HEAD PATCH OPTIONS CONNECT DELETE TRACE POST PUT
pattern
Type: String
or RegExp
Trouter supports simple route patterns which are fast and well readable but limited. If you need more complex patterns, you can pass an instance of RegExp
with parameters specified as named capture groups.
Important: RegExp named capture groups are supported in Node.js 10.x and above!
The supported route pattern types are:
- static (
/users
) - named parameters (
/users/:id
) - nested parameters (
/users/:id/books/:title
) - optional parameters (
/users/:id?/books/:title?
) - suffixed parameters (
/movies/:title.mp4
, movies/:title.(mp4|mov)
) - any match / wildcards (
/users/*
)
...handlers
Type: Function
The function(s) that should be tied to this pattern
.
Because this is a rest parameter, whatever you pass will always be cast to an Array.
Important: Trouter does not care what your function signature looks like!
You are not bound to the (req, res)
standard, or even passing a Function
at all!
trouter.use(pattern, ...handlers)
Returns: self
This is an alias for trouter.add('', pattern, ...handlers)
, matching all HTTP methods.
However, unlike trouter.all
, the pattern
you defined IS NOT RESTRICTIVE, which means that the route will match any & all URLs that start (but not end) with a matching segment.
router.use('/foo', 'USE /foo');
router.use('/foo/:name', 'USE /foo/:name');
router.post('/foo/:name', 'POST /foo/:name');
router.head('/foo/:name/hello', 'HEAD /foo/:name/hello');
router.find('GET', '/foo').handlers;
router.find('POST', '/foo/bar').handlers;
router.find('HEAD', '/foo/bar/hello').handlers;
Compare this snippet with the one below to see differences between trouter.all
and this method.
trouter.all(pattern, ...handlers)
Returns: self
This is an alias for trouter.add('', pattern, ...handlers)
, matching all HTTP methods.
However, unlike trouter.use
, the pattern
you defined IS RESTRICTIVE and behaves like any other trouter.METHOD
route. This means that the URL must match the defined pattern
exactly – or have the appropriate optional and/or wildcard segments to accommodate the desired flexibility.
router.all('/foo', 'ALL /foo');
router.all('/foo/:name', 'ALL /foo/:name');
router.post('/foo/:name', 'POST /foo/:name');
router.head('/foo/:name/hello', 'HEAD /foo/:name/hello');
router.find('GET', '/foo').handlers;
router.find('POST', '/foo/bar').handlers;
router.find('HEAD', '/foo/bar/hello').handlers;
Compare this snippet with the one above to see differences between trouter.use
and this method.
trouter.METHOD(pattern, ...handlers)
This is an alias for trouter.add(METHOD, pattern, ...handlers)
, where METHOD
is any lowercased HTTP verb.
const noop = _ => {}:
const app = new Trouter();
app.get('/users/:id', noop);
app.post('/users', noop);
app.patch('/users/:id', noop);
app.trace('/foo', noop);
app.connect('/bar', noop);
trouter.find(method, url)
Returns: Object
Searches within current instance for all method
+ pattern
pairs that satisfy the current method
+ url
.
Important: Parameters and handlers are assembled/gathered in the order that they were defined!
This method will always return an Object with params
and handlers
keys.
params
— Object whose keys are the named parameters of your route pattern.handlers
— Array containing the ...handlers
provided to .add()
or .METHOD()
Note: The handlers
and params
keys will be empty if no matches were found.
method
Type: String
Any valid HTTP method name, uppercased.
Note: When searching for HEAD
routes, GET
routes will also be inspected.
url
Type: String
The URL used to match against pattern definitions. This is typically req.url
.
Benchmarks
Run on Node v10.13.0
GET / x 10,349,863 ops/sec ±2.15% (93 runs sampled)
POST /users x 13,895,099 ops/sec ±0.40% (94 runs sampled)
GET /users/:id x 6,288,457 ops/sec ±0.25% (93 runs sampled)
PUT /users/:id/books/:title? x 6,176,501 ops/sec ±0.22% (96 runs sampled)
DELETE /users/:id/books/:title x 5,581,288 ops/sec ±2.04% (96 runs sampled)
HEAD /hello (all) x 9,700,097 ops/sec ±0.47% (90 runs sampled)
License
MIT © Luke Edwards