boysimple dimple boysimple dimple - 6 months ago 43
Node.js Question

How do I route a string to a function based on a regex match?

I'm working with an external application that posts an http request with this body on a single url

{ userToken: '***************',
token: '**********************',
name: 'app.install',
userId: 'u:******' }

Based on the 'name', I have different functions to handle the input. How do I route the request to the correct function?

In both Express and Django, regex is used to map the url to the handling function.

urlpatterns = [
url(r'^articles/2003/$', views.special_case_2003),
url(r'^articles/([0-9]{4})/$', views.year_archive),
url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),

In my case, the URL remains constant, but the name part of the JSON reply determines what needs to be done.

How do I route the 'name' value to a function?

My current approach is to use a long switch-case. I've seen some people simply use eval(), but that's a bad approach. Is there a way that works like the Django routing system?

  1. There is a tones of route parsers in npm. Get one you prefer.
  2. Create Map of routes-handler pairs.
  3. Iterate over map on request in for loop.

Example with npm's route-parser package:

const Router = require('route-parser');
const routes = new Map();

routes.set(new Router('/users/:id'), (params) => {
    return `id: ${}`;

function handleRoute(url) {
    for (let route of routes.keys()) {                       
        let match = route.match(url);
        if (match) {
            return routes.get(route)(match);

handleRoute('/users/1'); // -> 'id: 1'