Skip to content

ryanmorr/router

master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
src
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Router

Version Badge Build Status License

A minimalist universal router for web applications

Install

Download the development or minified version, or install via NPM:

npm install @ryanmorr/router

Usage

Create a router that matches different routes and extracts the parameters to pass to the callback functions:

import Router from '@ryanmorr/router';

const router = Router()
    .route('/', () => {
        // Handle home page 
    })
    .route('/foo', () => {
        // Handle "/foo"
    })
    .route('/foo/:bar', ({bar}) => {
        // Parameters are indicated by a prefixed colon
    })
    .route('/foo/:bar/:baz?', ({bar, baz}) => {
        // Optional parameters are indicated by a suffixed question mark
    })
    .route('/foo/qux/*', ({wildcard}) => {
        // An asterisk indicates a wildcard that will match anything
    });

// Find the route matching "/foo" and invoke the callback function
router.dispatch('/foo');

Use in a browser:

window.addEventListener('popstate', () => {
    router.dispatch(window.location.pathname);
});

Use in Node.js:

const http = require('http');
const url = require('url');
 
const server = http.createServer((req, res) => {
    const path = url.parse(req.url).pathname;
    router.dispatch(path);
});

server.listen(8888);

License

This project is dedicated to the public domain as described by the Unlicense.

About

A minimalist universal router for web applications

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published