2nd February 2012 at 8:27 · By Lee Jacobson

Node.js for beginners, part 1 - Hello world, and a bit of fun!

Introduction

This is the first part in a series of tutorials I want to write on Node.js. I should make it clear that I'm no expert on Node.js, but a good way to check you understand something is to try to explain it to someone else. If you see something that you don't think is quite right please let me know so I can correct the mistake, I'll make sure to give you credit.

I decided to learn Node.js recently due to its increasing popularity. The programming industry moves incredibly fast and it's dangerous to fall behind. Learning new languages is important because if you don't you're likely you'll get left behind and out of a job. Think about all of them flash developers who can't find any work anymore.

So lets begin with a little bit of information (blegh!).

Node.js is a server-side version of JavaScript. That means all the things all them cool things about JavaScript apply here. It also means if you're already quite familiar with JavaScript you're going to have a nice advantage. Node.js is only a few years old and that means even the people that have been working with it from the very beginning have only been using it for a few years. Compare this to how long some people have been writing in C. Being such a new language it also means there aren't many people out there who know it and that means from the simple rule of supply and demand your skill is worth more than your average PHP programmer.

Creating Hello World

Let's create a hello world. First head over to http://www.nodejs.org and download node.js. When it's installed and ready create a new JavaScript file with the following:

console.log("Hello World");

Now save the file, call it something like "hello.js" and run it with the following command:

node hello.js


So you should get 'Hello World' appear in your terminal. That's all good but I'm sure more importantly you want to know how to print 'Hello World' to new HTTP connections.

Open back up your text editor and type:

var http = require('http');

http.createServer(function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello World\n');
}).listen(8080);

console.log('Server started');

Now save your file and run it with:

node hello.js


You should see 'Server started' in the terminal. Great! Now open your web browser and go to 'http://localhost:8080' you should see your 'Hello World' message.

Let's take a closer look at our code.
The first line is just getting the http module and saving it to the variable 'http'. The http is included with Node.js to make it easy for us to create Node.js applications.

We can then use the http module to create our http server by calling it's function 'createServer'. This function returns an object and takes a function in a parameter.

We're calling the function 'listen' on our new server object which takes in a numeric value which tells our server what port we want it to listen on. In our case we're using port 8080 which is why we connected our browser to http://localhost:8080

We also create a function and use it as a parameter for the 'createServer' function. This is quite a standard thing to do in JavaScript because functions can be parameters just like variables and objects can be. What's going to happen is that every time our server receives and new connection on port 8080 it's going to run our function we gave it. Interestingly the function we are passing to it is called an anonymous function, and it's called this because we don't give it a name.

You might have noticed our anonymous function takes two parameters, 'request' and 'response'. These parameters get passed to our anonymous function by the HTTP server when it receives a new connection. They are both objects which we can use in our response to the incoming request.

You notice the first thing we do is call the 'writeHead' function this lets us set the HTTP status as the first parameter and send some response headers as a second parameter. We're setting status code 200 which is telling our web browser everything's OK and we're also passing it a 'Content-Type' header which lets our browser know what we're sending it. In our case it's just plain text.

Next we're using the response object to write our 'Hello World'. We do this by simply calling it's write function and passing it our text. At this point we're done with our response so we tell the response object by calling its 'end' function.

Making our response more interesting

Hello world is pretty boring so let's do something a little more entertaining. We can create a user counter very easily in Node.js and we don't even need to use a database like we might do in PHP.

Create a new JavaScript file called, 'counter.js' and type the following:

var http = require('http');

var userCount = 0;
http.createServer(function (request, response) {
    console.log('New connection');
    userCount++;

    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.write('Hello!\n');
    response.write('We have had '+userCount+' visits!\n');
    response.end();
}).listen(8080);

console.log('Server started');

Now let's run it with the command,

node counter.js


When you navigate your browser to 'http://localhost:8080' you should now get a view counter.

Note: You might see the counter going up by two for each request, this is because your browser is requesting the favicon from the server (http://localhost:8080/favicon.ico).
You should also see that Node.js is logging each request it receives to the console.

The main thing we're doing here is setting a 'userCount' variable and incrementing on each request. We're then writing the 'userCount' in the response text.

In PHP to do the same thing you would need to save the information to something like a text file or database.

This tutorial is also avalible in Chinese: http://www.laonan.net/blog/63/
Thanks to laonan for the translation

If you liked this tutorial check out part 2, Node.js for beginners - Callbacks

Author

Lee JacobsonHello, I'm Lee.
I'm a developer from the UK who loves technology and business. Here you'll find articles and tutorials about things that interest me. If you want to hire me or know more about me head over to my about me page

Social Links

Tags

Comments

blog comments powered by Disqus