[Node.js][JavaScript]A beginners guide

Post all your tuts or request for tuts here.
Post Reply
User avatar
Chris
Posts: 1580
Joined: Wed Sep 30, 2009 7:22 pm

[Node.js][JavaScript]A beginners guide

Post by Chris »

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).
Image

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:
Image
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
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:

Code: Select all

var http = require('http');
http.createServer( function (request, result)
{
	result.end('Hello World');
}).listen(80);
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'
Image
Now type in

Code: Select all

node.exe scripts/test1.js
or simply

Code: Select all

node scripts/test1.js
Image
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":
Image

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');
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.

Code: Select all

result.end('Hello World');
The 'listen' function called at the end simultaneously tells the server request to listen on port 80.

Code: Select all

listen(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.

Code: Select all

<?php
function foo()
{
    sleep(1); // do nothing for 1 second;
    echo 'World';
}
foo(); // call foo function
echo ' Hello';
?>
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:

Code: Select all

function foo()
{
	setTimeout( function()
	{
		console.log('World'); 
	}, 1000 ); // do this function after one second
}
foo(); 
console.log(' Hello');
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:

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');
?>
and its result:
Image
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());
And its result:
Image
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.
Fighting for peace is declaring war on war. If you want peace be peaceful.
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: [Node.js][JavaScript]A beginners guide

Post by Jackolantern »

Ooo, very nice, and thank you for making it Windows-based! I will have to sit down with Linux sometime and work on just learning the OS without trying to learn a new development platform at the same time.
The indelible lord of tl;dr
User avatar
Chris
Posts: 1580
Joined: Wed Sep 30, 2009 7:22 pm

Re: [Node.js][JavaScript]A beginners guide

Post by Chris »

Making it on windows saves me time too :D. Hope it doesn't bore you too much.. It is very basic. A static web-server is next.. Then sockets.
Fighting for peace is declaring war on war. If you want peace be peaceful.
User avatar
hallsofvallhalla
Site Admin
Posts: 12026
Joined: Wed Apr 22, 2009 11:29 pm

Re: [Node.js][JavaScript]A beginners guide

Post by hallsofvallhalla »

awesome!!

Can't wait to dig onto it.
gxxaxx
Posts: 9
Joined: Mon Mar 26, 2012 4:40 am

Re: [Node.js][JavaScript]A beginners guide

Post by gxxaxx »

FYI, I stumbled upon this youtube video with Ryan Dahl (creator of nodejs)

I found it really good introduction. And I enjoyed watching him. He is someone that you could easily hang with.

http://www.youtube.com/watch?v=jo_B4LTHi3I
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: [Node.js][JavaScript]A beginners guide

Post by Jackolantern »

Definitely a neat watch, but wow... you liked watching him? Nothing against him at all, but his nervousness actually made it a bit of an uncomfortable watch for me lol. Not that I could do any better. He is just your average hacker who's creation blew-up and suddenly he is in the public eye with basically 0 preparation for being in that position. Reminds me of some of Mark Zuckerburg's early conference talks when Facebook first started blowing-up haha.
The indelible lord of tl;dr
gxxaxx
Posts: 9
Joined: Mon Mar 26, 2012 4:40 am

Re: [Node.js][JavaScript]A beginners guide

Post by gxxaxx »

"He is just your average hacker who's creation blew-up"
That's why I liked watching him. I get tired of the suits with polished ties and patent shoes.
He is clearly not corporate --- in any fashion. He was just showing his stuff, as if he just came by the computer lab with a cool idea.
User avatar
Ark
Posts: 427
Joined: Wed Jun 01, 2011 10:25 pm

Re: [Node.js][JavaScript]A beginners guide

Post by Ark »

Thanks Chris this is a really good tutorial! Don't know why i didn't found this before!
Orgullo Catracho
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: [Node.js][JavaScript]A beginners guide

Post by Jackolantern »

gxxaxx wrote:"He is just your average hacker who's creation blew-up"
That's why I liked watching him. I get tired of the suits with polished ties and patent shoes.
He is clearly not corporate --- in any fashion. He was just showing his stuff, as if he just came by the computer lab with a cool idea.
I can appreciate that :) I just sometimes feel nervous for people who are visibly nervous lol. No idea why.

It is definitely neat to see coders with their creation they hoped at one point that maybe 10 people would find useful so it would have been worth their time, and now suddenly hundreds of thousands of devs are getting on board. It is always inspiring to every other coder out there!
The indelible lord of tl;dr
gxxaxx
Posts: 9
Joined: Mon Mar 26, 2012 4:40 am

Re: [Node.js][JavaScript]A beginners guide

Post by gxxaxx »

Yeah, the 10 people would be nice.
lol :lol:
Post Reply

Return to “Tutorials”