10. Node.js Lessons. Node.JS as a web server


Hey all! This time we will meet Node.js as a web server. So, let us create a new app for that purpose. Set up your editor in a way it would know you’re working on a Node.js project and support the respective auto-additions and global variables. Next let us create server.js and connect a module as the very first step:

We’ll talk later about this module in details, but right now we need just one object from it:

As we can see from its name, it can listen to an IP-port and answer incoming requests. To give it an IP-port use the following command:

And to answer requests the system uses events. The server is EventEmitter, and incoming requests initiate a respective event, which is called a request. Its handler gets two objects:

The first request is an incoming request that contains information sent by a browser including, in particular, an incoming request’s url. And the second parameter is the object’s answer. In the first one we read, in the second – we write. This function in particular ends making a request right at the moment sending the phrase: «Hello, world!». So, let us see how it works. For that purpose I will create a configuration in my WebSorm 2016 to launch the Node.js app. Select Node.js, it already contains the way to Node. Now we add a pass to the file that is currently being executed. Please, repeat the procedure, but in your own editor. Let us launch our server. It works!

Right now go to the browser url – . Great! Looks like everything is working. To make sure, create a variable

which will introduce a current counter of requests. I open the browser and try to update the page. But my efforts do not bring any result. Why? Node.js is constructed the way that upon launching and reading the module file – in our case it is the main  and the only file – Node creates a module object out of it and further uses this object. Respectively, when the file changes, Node simply does not consider these changes because the file has already been handled, and the module object is already done. To make Node re-read the file, the easiest way is to restart the server. But if I push play, the system will show me an error: EADDRINUSE. It means, the URL is already used because Node server.js has tried to restart once again, but had not ended actions of a currently working program. A previous server has already occupied this IP-port. What should we do? For example, you can edit the configuration by ticking “Single instance only” (the server can be started only as one). Push play again, and the program will suggest us to end the current start. I will ask the system not to notify be about this in the future, but just do it. Now every time when you push play or Ctrl+R a current server will be restarted without making a new one. If you work in console, this won’t be a problem at all. Kill the current Node.js and start a new one. Later we will learn how to optimize it.

Now I move to a browser and push Ctrl+R. As we see, a counter of requests shows a number two more than a previous one, instead of only one point greater. It happens because a browser makes one more request together with its own page. It gets done at url favicon.ico. In our case, we do not return favicon.ico, that’s why our browser repeats it every time. It turn out that one page update leads to two request – at least, in the current context, in Chrome.

We’ve completed our first server on Node.js. Further we will work to make it even more powerful and interesting. But before we continue, one note for you: if you check the very Node.js website, then an example similar to ours looks a little bit different there. The key difference is that new server is used here, while http createServer is used there. It is just the same. Here a request handler gets set up clearly, while there it is transmitted to the arguments. Arguments transmission is also a handler setup, the only difference is in this additional syntax. It is a bit shorter, but I’ve chosen this syntax as an example because it looks more obvious and shows what’s currently happening.

And now, if you were attentive, it won’t be a real problem for you to answer the following question. Here we’ve got a request event handler. Tell us, please, how can we say what other events are there for the server? When are they requested? In what order are they requested, when this request is being handled? But do not use our documentation, please! Why do I ask you not to use our documents? In fact, there are two reasons. First, it is more interesting. Second, the server (var server = new http.Server()  ), in fact, inherits net.Server of the net module, while it inherits EventEmitter:

// http.Servernet.ServerEventEmitter

So, now you know the hierarchy. And some server events are described here, in http.Server, while others – in the documents to net.Server:

By simply looking into a book you will hardly understand the event order. Now I will tell you how to do it. The hint is hidden in this string:

// http.Servernet.Server EventEmitter

The server is EventEmitter. It means, all events are generated with a server.emit request. Of course, we do not request this method by ourselves. In this case, it gets requested by Node.js, and we just set up the handlers. But nothing can stop us, if we want to change this method to our own. The emit method receives an event title and other data needed for this event:

In this case, these will be req, res. But we are interested only in event names, which we will output using console.log.  Next we will transmit this request to our initial emit method:

Let us take a look at what we’ve got as a result. Restart a server. And here we see the first event – listening. It means, the server has started to listen to connection:

Next I enter a browser and go to the URL. Note: I press Ctrl+R, and request gets greater, even two points greater. While there is only one (or two) connection and no new connections because this event happens, when a browser opens a new network connection to a server, and request sends a request. The browser is created in the way that it tries to use one network connection as much as possible. That is called Keep-Alive. The browser saves it and sends new requests using it.

So, we’ve created a simple web server, got familiar with the respective http.Server object and events that happen there.

You can find this lesson coding in our repository.


The lesson materials were borrowed from the following screencast.

We are looking forward to meeting you on our website soshace.com

About the author

Stay Informed

It's important to keep up
with industry - subscribe!

Stay Informed

Looks good!
Please enter the correct name.
Please enter the correct email.
Looks good!

Related articles

How I Built an Admin Dashboard with Python Flask

In this article, I will share the how I built an admin dashboard. I will give a step by step guideline on how I built this application with Python ...

Getting started with Git Hooks using ghooks

Git hooks are configured scripts that are executed at specific moments during git operations. ghooks is a package that configures git hooks so that ...

React Native vs. Flutter: Which One Would Suit You Better?

Unveiling pros and cons of such cross-platform development frameworks as Flutter and React Native. Discover what suits you ...

No comments yet

Sign in

Forgot password?

Or use a social network account


By Signing In \ Signing Up, you agree to our privacy policy

Password recovery

You can also try to

Or use a social network account


By Signing In \ Signing Up, you agree to our privacy policy