## I Create the node.js server

To create a server you just need three lines:

var http = require("http");
http.createServer(function (request, response) {
}).listen(9620);

The first line includes an additional library needed to set up the web server. The second line creates a server – there is an embedded callback with two entries:

request and response

request – that’s what the client has asked for

response – that’s what you will give to him

the last line says that the server is listening on a certain port, in this case 9620.

Understanding ports is not too difficult. Each port is like a telephone line

Our Internet communication runs on port 80, ftp on port 20, email on port 25

so they do not disturb each other so that at the same time you can upload a file (port 20), browse the Internet (port 80), and check your emails (port 25).

To start our server is easy. Let’s assume we call it “testserver.js”

Then we write

node testserver.js

The server starts – and it does not end, since we have entered an indefinite process

To see the difference, we create another file, called “hello_world.js”;

There is nothing in it, just

 console.log(“Hello World”);

when we run it we see the console printing hello world – and then the program breaks.

Why? Because it’s done – in contrast to the server which provides a loop that listens for incoming events

## II. Communicate with the Server

How can I communicate with the server?

I have to write a little client script, that gets executed.

First I need a minimal html page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>TITLE</title>

<body>
</body>
</html>

Since we need JQuery we add

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>TITLE</title>

<script src="jquery-1.10.2.js" type="text/javascript"></script>

jquery-ui.min.js" type="text/javascript"></script>
<script src="jquery-1.10.2.js" type="text/javascript"></script>

<body>

</body>
</html>

You don’t have to worry about it. This includes the library. The next thing is more interesting. We want to execute a hello when the file is loaded:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>TITLE</title>

<script src="jquery-1.10.2.js" type="text/javascript"></script>

type="text/javascript"></script>
<script src="jquery-1.10.2.js" type="text/javascript"></script>

<body>

<script type="text/javascript">$(document).ready(function () { alert("Hello"); }); </script> </body> </html> This executes an alert when the document is loaded. Usually you would outsource this process in a different file – but for our purpose it is nice to keep all our stuff in one single fie. ## III. Client Now our client is ready to communicate with the server (given that the server is already running. We can write a little function. We don’t even have to store it, we can use the console instead. Open it up in your browser typing F12 function communicate() { var url = “127.0.0.1:9020”;$.ajax({

type : "GET",

url : url

}).done(function(msg) {

console.log(“waiting for an answer”);

})

}

This is a very interesting function since it contains a so called callback function.

First we see this line:  var url = “http://127.0.0.1:9020”;

It just tells our client the address he should contact.

127.0.0.1 means – our server program is running on our local computer

the addition :9020 tells it that we can reach him on port 9020.

Then we have the JQuery function (you can see a dollar – and that’s indicating this is JQuery

$.ajax({ }); It takes two parameters, first the url (the address) we want to contact, second the type of request. In our case it is a GET. We want to GET some information. Ok – we type it into the console. Now it’s known and we can invoke it: communicate(); When you look at your server console we see that something has happened By the way we could have chosen another function also: var url = 'http://philipp-burckhardt.com:9620';$.getJSON(url, function(data) {

console.log(“Here comes a reponse”);
})

Okay. That’s fine.

Still the question remains: Why don’t we get an answer.

Have a look at the server again:

var http = require("http");

http.createServer(function (request, response) {

}).listen(9620);

We still have an empty function – but we could find out if somebody contacted us by just writing a single line into our function. Like this:

var http = require("http");

http.createServer(function (request, response) {

console.log("Hi, there is an outer world");

}).listen(9620)

var http = require("http");

http.createServer(function (request, response) {

if(request.method  'GET')

{

console.log("This is a request method");

}

}).listen(9620)

This gets pretty interesting. We see that the request is an object itself and that it can identify, that we want to GET information. But what kind of information? Can we be more precise?

var url = 'http://philipp-burckhardt.com/twitter_feeds';

$.getJSON(url, function(data) { console.log(“Here comes a response”); }) Fine. But then we have to change our server too. var http = require("http"); var url = require("url"); http.createServer(function (request, response) { if(request.method 'GET') { console.log("This is a request method"); var pathname = url.parse(request.url).pathname; console.log("What you want is: " + pathname); } }).listen(9620) We see 3 changed lines. First we see below our http-library another one: var url = require("url"); This is – as we can assume – is a library for the url string. In fact that’s what we want, since we want to differentiate between our web address and the following, more precise get statement twitter_feeds. That we precise our call is indicated by the /. Let’s have a look what our server does. Find – he gives us the answer: /twitter_feeds That’s great. Now we can differentiate and have multiple GET- requests which may on server side be handled differently. Ok – let us prepare a mechanism for that: http.createServer(function (request, response) { if(request.method 'GET'){ var pathname = url.parse(request.url).pathname; switch(pathname) \t{ case '/twitter_feeds': console.log("invoke a function"); break; default: console.log("You want " + pathname); break; \t} } }  This is pretty straightforward. We have a pathname – and now we split it into a switch that could invoke various functions we can arbitrarily define in the code. But – remember. Our client still gets no answer. How can we achieve that? First we change the announcement line console.log(“invoke a function”) so that it actually triggers a function: http.createServer(function (request, response) { if(request.method 'GET') { var pathname = url.parse(request.url).pathname; switch(pathname) { case '/twitter_feeds': answer(response); break; default: console.log("You want " + pathname); break; \t } } } But we have to add this answer function, like this: function answer(response) { response.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin' : '*', }); var t = JSON.stringify("Hi, I am speaking JSON"); response.end(t); What we note first is that fact that we do not only invoke a function but pass a parameter called response. Where does it come from? If you have a look at the original http server function you will notice two parameters, request and response. Request meant what the client was calling for – the response is created whenever the server gets a request. That’s why we can pass it to our answer function. And we must. Otherwise we will not be able to answer. Let’s have a look how we do it. response.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin' : '*', }); This looks pretty complicated. First thing we note is that there is something like a response-header, in this case the number 200. 200 means ok I am pretty sure you know the error code 404 (which means a page is missing). So the 200 is of that kind as well as all the other server messages: 204 No Content 206 Partial Content 400 Bad request 401 unauthorized There’s a long list of possible answers – and they are all related to the http-protocol. In our case everything is ok – therefore we answer with the status code 200. And that’s why our client function knows it ok. Before it reads the message it would analyze the header and then patch it to the respective handlers. Inside the response we see another line: 'Content-Type': 'application/json', That’s self explaining. We say we want to give back a JSON format. That’s comparable to somebody answering in Chinese but holding up a sign telling THIS IS CHINESE. That’s it. He tells us he’s talking Chinese and not Korean. Nevertheless, JSON might seem quite complicated at first. But it’s simple. Data in JSON format looks like Javascript, but we have to encode it anyway. That’s what the following line does: var t = JSON.stringify("Hi, I am speaking JSON"); It translates a string into JSON. The great thing with JSON that it can read whole Javascript objects, like this one: javascript var message = {}; message.type = 200; message.str = “I am a message”; var t = JSON.stringify(message); console.log(t);  Now type this into your console and see what you get: {"type":200,"str":"I am a message"} It’s our object – but it is organized into pairs, so called hashes. “type”:200, “str”:“I am a message” If you are familiar with JQuery this looks familiar to you. So our server does not speak Chinese, but he speaks JSON. Although it looks pretty JavaScript-like we have to parse it to make it a JavaScript object again. That’s easy: var x = JSON.parse(t); creates an object again. Now we have an idea how the server and the client might interact, but there was another line we have to understand: ‘Access-Control-Allow-Origin’ : ‘*’, This is something really crucial, because by this line we can control who is going to call our server. In this case there is no limit at all. But we could do this if we changed this line: ‘Access-Control-Allow-Origin’ : ‘http://my_simple_server.com’, So just the people connecting from ‘http://my_simple_server.com’ would get an answer, the rest would be simply ignored and forced to wait forever. Forever? Not really. When our client asks for an answer we can see him waiting/spinning in the console – but after a while he would give up. In our case everything is fine – we get our data. Have a look at our function: $.getJSON(url, function(data) {
console.log("I got an answer " + data);
})

The first line looks pretty awkward since we can find a function beside a parameter.

That’s a so called callback function – and it’s syntax is like this

function do_something(parameter, function(data) {
})

See how it works – the second parameter is replaced by a function, which contains another parameter.

How is it working? The thing is that our getJSON function is a TAKE and GIVE function. It expects a parameter – a url – and gives back some data.

Since scanning a database might take a while this is called an asynchronous function. We cannot reliably say how long it will take.

Here’s an example.

\$.getJSON(url, function(data) {

console.log("I got an answer " + data);

})

console.log("LAST LINE");

Intuitively we may assume that the LAST LINE is executed last. But that’s not the case. In fact the answer will appear after the console has announced the LAST LINE.

That is because we have to wait for the server to answer our request. And now we may understand why the function is nested inside the other function, it is invoked when the server has given his answer.