basic node server (pt 1)

We first start at index.js. Basically it first requires the module files ‘server’ and ‘router’ and recognizes the interface and definition implemented in those files. It puts the function definitions and variables into global var server an router for us to use later.

Hence that’s why you will see the console.logs of those files


start of index.js
start of server.js
end of server.js
start of router.js
end of router.js

…then after requiring those files, we get display the log:
‘server variable running function start with parameter router’

Our variables to use are server and router.

in index.js

We now use the server variable to call function start.

The whole point of router.js is to provide the function route, which we pass into the server.start for it to use in its onRequest function.

in index.js

As you will see later, each request that comes from a browser gets taken care of by onRequest. And onRequest uses the route function in order to show user the url path.

in server.js

In other words, we pass it in simply so that it is a variable that can be used in the start function. The start function’s function onRequest(request, response) directly uses the route function.

function onRequest(request, response) is just a function definition of start function and does not get used yet.

We have our global variable http and call its function createServer, specifying that we want to create a server and it listens for user requests at port 8888.

We then pass in the onRequest function as a parameter to createServer to let it know what function to use to process when a request comes in.

Start up your servers by opening up a terminal, going into the directory where index.js, server.js, and router.js are located, and in your terminal type:


node index.js

you should see that the server will start.

Rickys-MacBook-Pro:nodeProject1 $ node index.js
start of index.js
start of server.js
end of server.js
start of router.js
end of router.js
server variable running function start with parameter router
server.js – start function:
[Function: route]
server.js – Server has started. end of start function
end of index.js

Then open up a browser and type in:

localhost:8888/test

You will then see result in your terminal:

server.js – start of onRequest function
server.js – request.url: /test
router.js – about to route a request for /test

full code

index.js

server.js

router.js