[Node.js][JavaScript]A beginners guide
Posted: Wed Oct 19, 2011 9:29 pm
This tutorial is aimed at people who have a basic understanding of JavaScript or other languages and makes comparisons between JavaScript and PHP.
I'm not going to bore you with too many details to start and will just keep it short.
Node.js is an engine that allows you to run JavaScript as a server side language, just like PHP, Perl, Python or any other language you can think of.
To start this tutorial you will need a copy of Node.js. In this example I'm using Windows as I'm pretty sure most people reading this are doing so on a Windows system.
Here's a working link to V0.5.9 .exe: http://nodejs.org/dist/v0.5.9/node.exe for other downloads and documentation visit http://nodejs.org/.
If you run this program you will notice it's just a command line window. In this window we can type JavaScript. Go ahead and type a math sum or something and it will give you a result. You can also make variables and whatnot. Use the '.clear' command to erase everything.
Bellow is an example where I've made two variables variable 'a' which contains 1, and variable 'b' which contains 2. I then add them both together and the result is 3. (Note: I've changed the colour of my prompt to make it easier to read).

Before we start any scripting I'm going to explain the setup I use throughout my Node.js tutorials. You could set it in your command line environment variables if you want but because this is still an unstable version I've decided not to. If you understand how to set it up you can skip this step.
First I've saved node.exe in it's own directory on my desktop called 'Nodejs'. Go ahead and do this. Inside this directory I have another directory called 'scripts'. Go ahead and make that.
Once we have that set up we'll have something that looks like this:

We can now call Node.js from in my case 'C:\Users\Chris\Desktop\Nodejs\node.exe'.
Before we start scripting I'm going to explain a few things to the people who aren't used to working in a command line. With node.exe we can type in all the things we would ever need to to run our servers and everything else. This is however a very unhandy way of working. It's much easier to write a script, save it and then run it. We do so by first writing a script and calling it through the windows command line like this:
This means we can run JavaScript using node.exe through the windows command line. So lets write our first script.
Open your favorite text editor or JavaScript IDE and save the following script as test1.js inside the scripts directory:
Now open the windows command prompt (WinKey+R, type 'cmd' and hit enter) and change your directory using the 'cd' command, to where you have node.exe saved. In my case 'C:\Users\Chris\Desktop\Nodejs'

Now type in
or simply

You will most likely be asked to allow access by your firewall. Go ahead and allow this. This is happening because the script is wanting to listen to incoming calls on port 80. Also make sure there are no other servers running on port 80.
Now open your browser and visit http://localhost/ or http://127.0.0.1/. If everything has went as planned you should now be reading "Hello World":

So what exactly is this script doing?
First we are requiring the HTTP library. And storing the http class as a new instance in a variable called 'http':
After this we are calling the 'createServer' event which creates a new web server object. I'll not bore you with too many details, but the request and result parameters do pretty much what they are called. These parameters pass the request and result instances to the function and allow us to do all sorts of fun stuff to the server request.
The 'listen' function called at the end simultaneously tells the server request to listen on port 80.
So we've now made a web-server with Node.js and are all excited that we have something working! Lets start with the boring stuff! I personally hate writing this bit of tutorials and I'm sure you guys hate reading it as there is so much reading to do and such little action, but this part is important to start to understand what makes Node.js different from other languages.
If you have experience with JavaScript you will know that everything happens when other things also happen.. If you've ever heard of asynchronous and synchronous you'll know straight away what I mean.
First lets look at an example in PHP.
What this script basically does is first calls a function foo(). foo() stops the script for 1 second and then echo's 'World', after this function is finished PHP then echo's ' Hello'. The result would be 'World Hello' after around one second.
If we were to write the exact same in JavaScript it would look something like this:
What you might expect from this is the exact same result as PHP would give. But the result is actually different. What happens is when foo() is called on line 8.. there is a timeout set for one second. During this timeout.. rather than waiting.. JavaScript also calls the console.log() function on line 9. Resulting in ' Hello' being logged and 'World' being logged one second later.
Here's a PHP script:
and its result:

Here's a JavaScript script run with node:
And its result:

Notice that the last line was called but the timeout wasn't finished yet. This opens a door to a whole new way of thinking when programming server side. Understanding this is one of the most important things to understand when using Node.js. What this means is we can fully utilize the new HTTP 1.1 which is part of the HTML5 standard. What this standard is, is rather than closing a connection between a server and client.. We can keep it open.
Further there are quite a few more advantages to using JavaScript as your server-side language. One of the bigger ones being that JSON can be interpreted without needing to be parsed into another language. This reduces memory usage and speeds up data transfer. This alongside a database that stores information as JSON like CouchDB or MongoDB make a perfect combination. No more slow SQL to be parsed.. JSON is sent.. JSON is checked.. JSON is saved.. It's that simple.
I'm not going to bore you with too many details to start and will just keep it short.
Node.js is an engine that allows you to run JavaScript as a server side language, just like PHP, Perl, Python or any other language you can think of.
To start this tutorial you will need a copy of Node.js. In this example I'm using Windows as I'm pretty sure most people reading this are doing so on a Windows system.
Here's a working link to V0.5.9 .exe: http://nodejs.org/dist/v0.5.9/node.exe for other downloads and documentation visit http://nodejs.org/.
If you run this program you will notice it's just a command line window. In this window we can type JavaScript. Go ahead and type a math sum or something and it will give you a result. You can also make variables and whatnot. Use the '.clear' command to erase everything.
Bellow is an example where I've made two variables variable 'a' which contains 1, and variable 'b' which contains 2. I then add them both together and the result is 3. (Note: I've changed the colour of my prompt to make it easier to read).

Before we start any scripting I'm going to explain the setup I use throughout my Node.js tutorials. You could set it in your command line environment variables if you want but because this is still an unstable version I've decided not to. If you understand how to set it up you can skip this step.
First I've saved node.exe in it's own directory on my desktop called 'Nodejs'. Go ahead and do this. Inside this directory I have another directory called 'scripts'. Go ahead and make that.
Once we have that set up we'll have something that looks like this:

We can now call Node.js from in my case 'C:\Users\Chris\Desktop\Nodejs\node.exe'.
Before we start scripting I'm going to explain a few things to the people who aren't used to working in a command line. With node.exe we can type in all the things we would ever need to to run our servers and everything else. This is however a very unhandy way of working. It's much easier to write a script, save it and then run it. We do so by first writing a script and calling it through the windows command line like this:
Code: Select all
path> program.exe script.ext
Open your favorite text editor or JavaScript IDE and save the following script as test1.js inside the scripts directory:
Code: Select all
var http = require('http');
http.createServer( function (request, result)
{
result.end('Hello World');
}).listen(80);

Now type in
Code: Select all
node.exe scripts/test1.js
Code: Select all
node scripts/test1.js

You will most likely be asked to allow access by your firewall. Go ahead and allow this. This is happening because the script is wanting to listen to incoming calls on port 80. Also make sure there are no other servers running on port 80.
Now open your browser and visit http://localhost/ or http://127.0.0.1/. If everything has went as planned you should now be reading "Hello World":

So what exactly is this script doing?
First we are requiring the HTTP library. And storing the http class as a new instance in a variable called 'http':
Code: Select all
var http = require('http');
Code: Select all
result.end('Hello World');
Code: Select all
listen(80);
If you have experience with JavaScript you will know that everything happens when other things also happen.. If you've ever heard of asynchronous and synchronous you'll know straight away what I mean.
First lets look at an example in PHP.
Code: Select all
<?php
function foo()
{
sleep(1); // do nothing for 1 second;
echo 'World';
}
foo(); // call foo function
echo ' Hello';
?>
If we were to write the exact same in JavaScript it would look something like this:
Code: Select all
function foo()
{
setTimeout( function()
{
console.log('World');
}, 1000 ); // do this function after one second
}
foo();
console.log(' Hello');
Here's a PHP script:
Code: Select all
<?php
echo 'Script started at ' .date('H:i:s') . "\n";
function foo()
{
sleep(1); // do nothing for 1 second;
echo "World";
}
foo();
echo " Hello\n";
echo 'Script ended at ' .date('H:i:s');
?>

Here's a JavaScript script run with node:
Code: Select all
date = new Date();
console.log('Script started at ' + date.toTimeString());
function foo()
{
setTimeout( function()
{
console.log('World');
date = new Date();
console.log('Script ended at ' + date.toTimeString());
}, 1000 ); // do this function after one second
}
foo();
console.log(' Hello');
date = new Date();
console.log('Last line called at ' + date.toTimeString());

Notice that the last line was called but the timeout wasn't finished yet. This opens a door to a whole new way of thinking when programming server side. Understanding this is one of the most important things to understand when using Node.js. What this means is we can fully utilize the new HTTP 1.1 which is part of the HTML5 standard. What this standard is, is rather than closing a connection between a server and client.. We can keep it open.
Further there are quite a few more advantages to using JavaScript as your server-side language. One of the bigger ones being that JSON can be interpreted without needing to be parsed into another language. This reduces memory usage and speeds up data transfer. This alongside a database that stores information as JSON like CouchDB or MongoDB make a perfect combination. No more slow SQL to be parsed.. JSON is sent.. JSON is checked.. JSON is saved.. It's that simple.