Book Image

Node.js By Example

By : Krasimir Tsonev
Book Image

Node.js By Example

By: Krasimir Tsonev

Overview of this book

If you are a JavaScript developer with no experience with Node.js or server-side web development, this book is for you. It will lead you through creating a fairly complex social network. You will learn how to work with a database and create real-time communication channels.
Table of Contents (13 chapters)
12
Index

Implementing the router


Almost every web application needs a router, which is a component that acts as a front door and accepts the incoming queries. It analyzes the parameters of the request and decides which module of our system will serve the result.

We are using JavaScript language in the backend (via Node.js) and frontend (interpreted by the web browser). In this section, we will write a router that works in both the sides of our application. Let's start examining what the Node.js part needs:

// frontend/js/lib/Router.js
module.exports = function() {
  return {
    routes: [],
    add: function(path, handler) {
      // ...
    },
    check: function(fragment, params) {
      // ...
    }
  }
};

Router.js exports two methods. The first one registers routes by accepting a path and a handler function, which will be called if the current URL matches the path. The check function simply performs the actual check.

Here is how the add method looks:

add: function(path, handler) {
  if(typeof path...