basic node server (pt 3) – request handlers w/non-blocking op

We will inject the response object (from our server’s callback function onRequest()) through the router into the request handlers. The handlers will then be able to use this object’s functions to respond to requests themselves.

First we create an object. An an object in javascript is like a key/value dictionary, where we match keys and values up.

In our case, let’s create a handler object where we basically have the URL as the keys and the names of the functions that corresponds to those URLs as the value.

index.js

The server’s start takes route function parameter and handle object parameter. The handle object was declared in index.js.

The route is a function variable that takes in the handle object, the response object, and pathname that’s in server.js.

It then processes the requests and outputs data using these objects.

Server

From index.js, we remember that handle[“/”] maps to a requestHandler.function1
handle[“/start”] maps to another requestHandler.function2…so on and so forth

Hence, in our case, the pathname represents the user’s path for their request…..and handle[pathname] is the name of the function we will call.

We first want to make a simple check to see if handle[pathname] is indeed in fact a function, if it is…then we call the function like so:

where we throw in the response obj so that we can output to the browser whatever data we get.

router.js

requestHandler.js

Basically the function definitions that responds to the user’s request URLs.
We only provide 2: start and upload, which corresponds to
localhost:8888/start and localhost:8888/upload

1) We use dependency injection of the response object and have it output back to the browser the data we get.

2) We use child processes to make it non-blocking