ServerRouter

Server/Router.mjs

A standalone HTTP router that's based on the principle of middleware. Based on rill (see the npm package bearing the name), but stripped down and simplified.

new ServerRouter(verbose: Boolean)
Parameters
verbose (Boolean = false) Whether to be verbose and log a bunch of things to the console. Useful for debugging.
Instance Members
verbose
any(pathspec, action)
head(pathspec, action)
get(pathspec, action)
post(pathspec, action)
put(pathspec, action)
delete(pathspec, action)
options(pathspec, action)
on(methods, pathspec, action)
on_all(action)
onif(test, action)
handle(request, response)
iterate()

Contains context information about a single request / response pair.

new RouterContext(in_request: any, in_response: any)
Parameters
in_request (any)
in_response (any)
Instance Members
querystring
request
response
url
params
send
env

Helper methods for quickly sending responses to clients.

new Sender(response: http.ServerResponse)
Parameters
response (http.ServerResponse) The response object to use when sending requests.
Instance Members
html(status_code, template_filename, data)
html_string(status_code, html_string)
json(status_code, obj)
string(status_code, type, str)
empty(status_code)
plain(status_code, data)
redirect(status_code, new_path, message)

Holds request environment and state variables.

new RequestEnvironment(request: any)
Parameters
request (any)
Instance Members
logged_in
username
cookie
body

pathspec_to_regex

Shared/Pathspec.mjs

Converts a path specification into a regular expression. Originally from the server-side sibling of this (client-side) router.

pathspec_to_regex(pathspec: string, verbose: Boolean): RegExp
Parameters
pathspec (string) The path specification to convert.
verbose (Boolean = false) Optional. Whether to be verbose and log some stuff to the console. Default: false
Returns
RegExp: The resulting regular expression

ClientRouter

Client/Router.mjs

Client-side request router. You should use this in a browser. If you're not in a browser, you probably want ServerRouter instead.

new ClientRouter(options: object)

Extends EventEmitter

Parameters
options (object) The options object to use when creating the router.
Properties
verbose (Boolean) : Whether to be verbose and log debugging information to the console.
listen_pushstate (Boolean) : Whether to listen to the browser's pushstate event and automatically navigate on recieving it.
Instance Members
handle_popstates
add_404(callback)
add_page(routespec, callback)
navigate(path)
navigate_current_hash()

Namespaced logging manager.

Logs to stdout.

new NamespacedLog(namespace: any)
Parameters
namespace (any)

Generates various VT100 ANSI escape sequences.

Ported from C#.

This is a powahroot-internal class that @sbrl copies across various projects, but can be used outside. There is no guarantee of stability, though this API has been pretty stable.

Author: Starbeamrainbowlabs GitHub: @sbrl | Twitter: @SBRLabs | Reddit: u/Starbeamrainbowlabs **** Changelog ***** 27th March 2019:

  • Initial public release 9th March 2020:
    • Add Italics (\u001b[3m])
    • Export a new instance of it by default (makes it so that there's 1 global instance) 5th September 2020:
  • Add support for NO_COLOR environment variable https://no-color.org/ 24th January 2025:
    • Wow, this class has been used in a lotta places!
    • Add support for FORCE_COLOR env var (no standard)

new Ansi()
Author: Starbeamrainbowlabs
Instance Members
enabled

Simple logging class

This is a powahroot-internal class, but can be used outside. There is no guarantee of stability, though this API has been pretty stable.

new Log()
Author: Starbeamrainbowlabs

Middleware for logging requests to stdout.

middleware_log_requests(ctx: RouterContext, next: Function): void
Parameters
ctx (RouterContext) The router context to operate on.
next (Function) The next() function that is provided by powahroot.
Returns
void:
Example
import { ServerRouter, middleware_log_requests } from 'powahroot/Server.mjs';

// ...

const router = new ServerRouter((typeof process.env.DEBUG_ROUTES) === "string");

// Note that ordering matters here! If they were called the other way around then the `.get()` call would be called first before the logger has been registered!
// Note also that you would want to register the error handler BEFORE the logger.... because in the unlikely event the logger crashes it would otherwise bring down the entire server!
router.on_all(middleware_log_requests);
router.get(`/some_other_route`, another_handler);

Handles errors thrown by handlers further down the chain.

middleware_catch_errors(context: RequestContext, next: Function)
Parameters
context (RequestContext) The RequestContext object.
next (Function) The function to call to invoke the next middleware item
Example
import { ServerRouter, middleware_catch_errors } from 'powahroot/Server.mjs';

// ...

const router = new ServerRouter((typeof process.env.DEBUG_ROUTES) === "string");

// Note that ordering matters here! If they were called the other way around then the `.get()` call would be called first before the error handler has been registered!
router.on_all(middleware_catch_errors);
router.get(`/some_other_route`, another_handler);

Middleware that reads the request body from the client, parses it as JSON, and attaches it to context.env.body. Does nothing if the client doesn't set the correct content-type of application/json.

IMPORTANT: Unlike the other builtin middlewares, this is a function that returns the REAL middleware function! This is because we need some way to pass options to it elegantly without requiring function binding etc which looks bad.

middleware_parse_json(max_length_body: number): function
Parameters
max_length_body (number = 2*1024*1024) The maximum length of the client body to accept before returning a HTTP error 413 content too large. Defaults to 2MB,
Returns
function: The real middleware function.
Example
import { ServerRouter, middleware_parse_json } from 'powahroot/Server.mjs';

// ...

const router = new ServerRouter((typeof process.env.DEBUG_ROUTES) === "string");

// Note that ordering matters here! If they were called the other way around then the `.post()` call would be called first before the JSON parser middleware has been registered!
// Note also that you would want to register the error handler BEFORE the JSON parser.... because in the event the JSON parser crashes it would otherwise bring down the entire server!
router.on_all(middleware_parse_json(100)); // Allow a max of 100 BYTES of JSON
router.post(`/some_other_route`, another_handler);