Zrzut ekranu 2015-04-29 o 13.35.38

Simple node.js server

Dawid Cedrych
Follow me
Dawid Cedrych
Follow me

Latest posts by Dawid Cedrych (see all)

Let’s take a look at how to create a simple node.js server. The additional feature of presented server is responding with the text provided by user from console.

As a first step we have to declare some variables:

The first variable is just importing the http module. This is very common syntax in node.js with require(). The next two variables are quite straightforward; ‘text” is going to be a response of the server and “i” is just the helper counter used in upcoming for loop.

Now, we have to think about getting our text from console, suppose our file would be named simpleServer.js, the console command would look as follows:

where “this is my server” is the example of custom text.

Let’s see how to deal with it:

We need to iterate over process.argv, cast each element to string and concatenate to the text variable. The question that emerges is: Why should we start the iteration at index nr 2, which is actually the third element? Look once more on the console command:

The text we want to pass through the server starts at third position with the word “this”. Consider iterating from 0 index, what would be the result? Obviously “node simpleServer.js this is my server” instead of “this is my server”.

Ok, we are done with getting the text from console, let’s move forward:

Creating server is done in callback function, what shouldn’t be suprising since most of things are implemented this way in node.js. I think the first line inside the callback function needs more attention, let’s quickly dive into node.js docs and find out what is actually happenning there:

Sends a response header to the request. The status code is a 3-digit HTTP status code, like 404. The last argument, headers, are the response headers. Optionally one can give a human-readable statusMessage as the second argument. This method must only be called once on a message and it must be called before response.end() is called. If you call response.write() or response.end() before calling this, the implicit/mutable headers will be calculated and call this function for you.

If this is not clear enough(I believe it might be not), here is the link to node.js docs.

Then, we just write our text variable and end response with response.end().

The last line with console.log is not mandatory there, however, it gives user the information about where the server is actually running. This might be useful as nobody, who isn’t you and don’t know which port weas chosen, would like to search the js file looking for it.

Full code:

Some Screenshots:

Zrzut ekranu 2015-04-29 o 13.29.10 Zrzut ekranu 2015-04-29 o 13.28.55


Thanks for reading and if you have any questions, just leave the comment below or contact me via twitter!

Dawid CedrychSimple node.js server