Getting Started with Node.js
Getting Started with Node.js
Written by Mike James   
Monday, 28 November 2011
Article Index
Getting Started with Node.js
Event driven UI



Notice that the program doesn't end after the console.log command. The webServer object still exists and is waiting for a client to make a request so that it can call the response function. To stop the web server simply press Ctrl-C.

This is an example of event driven programming and if you have used almost any modern programming language that has a graphical UI you will have encountered it before.

When you create an even driven UI you place button object on a form and write a click event handler for it. When you run the program it doesn't stop after creating the button. Instead it waits until the button is clicked and then handles the event by invoking the event handler.

Node.js works in the same way - you created the web server object and specified an even handler. This waits for the event and calls the handler which in this case supplies the response to the client.

To show you that this really is how things are working let's create two web servers listening on two different port numbers -

var http = require('http');
var webServer1=http.createServer(
function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'});
res.end('Hello World from server 1\n');
var webServer2=http.createServer(
function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'});
res.end('Hello World from server 2\n');

webServer1.listen(1337, "");
console.log('Server 1 running at');

webServer2.listen(1338, "");
console.log('Server 2 running at');

Now we have one server listening for a connection on port 1337 and another on port 1338. If you point a browser at the first address you will see the first message and if you point it at the second address you will see the second message.

You can think of the two web servers as being like two buttons each with a distinct event handler waiting for a TCP connection to occur on their particular port.

Having two web servers on different ports isn't a likely operating scenario, but you can see how easy it is to "bind" a server to a port. This works just as easily if you want to work lower down the stack with a socket say. This ease of setting up asynchronous listeners for communications protocols is one of the strong points of Node.js.

Reading the headers

Now you have seen the basic operating principle of Node.js you can probably work out how to create more useful programs.

As a slightly larger final example consider the problem of sending back the headers in a request to the client.  In this case we can write a standalone response function:

var http = require('http');
var response=function(req,res){

The minimum html we have to write to get a page to display is the <html> tag:

res.writeHead(200, {
"Content-Type": "text/plain"});

Next we get the headers as an object with one property for each header:

var headers=req.headers;

Next we use a for loop to step though each one in turn and send the header name and value to the output page:

for(h in headers){
res.write(' <br/> ');

Finally we close the <html> tag and send the response to the client:


To actually create the server we need:

var webServer=http.createServer(response);
webServer.listen(1337, "");
console.log('Server 1 running at');

That is all there is to it. If you start the new program running you can point a client browser at it to see the headers sent to the server.

The example could have been written in a much more compact style by defining the response function in place and grouping the write methods into fewer calls but this doesn't fit the purpose of an example.

Where next?

Now you have seen Node.js in action how to expand what you are doing should be obvious. There are lots of modules to explore in the documentation, including file system handling, cryptography, sockets and so on. Node.js is still short of a lot of capabilities in the official modules but there are also third party modules that fill many of the gaps - mysql access, HTML parsing and various web frameworks.

What Node.js is good at, however, is when you want to create a web application that needs to implement Ajax like updates or where you need to communicate via custom protocols with the client. Node.js isn't the best choice for all applications but the main reason for this is that it is still very young and lacks the well developed frameworks that you will find in other technologies.

You can't deny that it's an interesting way to do things and the advantage of being able to use the same language at both ends of a transaction is worth a lot.

More Information


Node.js - Now With Added Windows

To be informed about new articles on I Programmer, subscribe to the RSS feed, follow us on Google+, Twitter or Facebook or sign up for our weekly newsletter.



Asynchronous Code In JavaScript

Events are central to the programming in JavaScript and most programmers master their use early on. Asynchronous programming is just another aspect of an event driven environment, but this is much mor [ ... ]

jQuery 3 - Using Events

jQuery provides both a general framework for handling events and event-specific functions. While you can use the general functions - on, off and one - to deal with all events, the event-specific funct [ ... ]

Other Articles

Last Updated ( Monday, 28 November 2011 )

RSS feed of all content
I Programmer - full contents
Copyright © 2017 All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.