Getting started with Node.js or Hello World in JavaScript

Node.js has got a whole lot of attention for some time now, and I guess it is time for me to get myself an opinion on what it is, and why it is so cool. And while doing so, I will try and write some blog posts offering my opinion and learnings regarding the platform.

In this first post, I will walk through setting up the “environment” needed to build apps, build an initial “Hello World” app to see that it al works. But let’s start with the first question you will ask if you have never worked with Node. What is Node? Well, it is basically a application runtime built on Chrome’s JavaScript runtime called V8. And what does that mean? Well, it means that you get a way to run JavaScript efficiently outside of the browser.

One of the most talked about feature is its non-blocking I/O model that basically makes more or less everything asynchronous, offering a very efficient platform to build applications on. In particular, it makes for an awesome platform for building webservers on…

The next question is obviously “How do I get started?”. Well, it is actually ridiculously simple. As there is no big server back-end or complex development environment to get up and running, instead it is just a matter of getting hold of the Node runtime, which is a breeze. Just head over to Nodejs.org and download the version you need. And by “version you need”, I mean the version needed to run on your choice of OS. Node can run on MacOS X, Linux and Windows.

See…even Windows is getting some love from this platform. And yes, I had to go there. Lately it seems like most cool, new things end up on Windows long after the other platforms… However, Microsoft seems to working hard to change this. At least in the developer area. And when it comes to Node, Microsoft has even gone as far as make it a first class citizen on Azure. Event so much that .NET might get jealous soon…

In my case, I am running a 64-bit Windows 8 machine, so I choose the 64-bit Windows Installer. You could go for the binaries only, but I like installers… :)

After having run the installer, you end up with a bunch of files in the “Program Files (x86)” folder. That’s it… No fancy search bar in your browser or anything… And what are the files that are installed? Well, mainly, you get an executable called node.exe, which is the Node runtime. Besides that you get a node module called NPM, which I will get back to sometime in the future… But for now, all you need to know is that it is a package manager. And if you come from .NET, you can consider it the NuGet of the Node world…

Ok, so now we have Node installed, so I guess it is time to see the magic in action. And to do that, we need an application. So let’s start building the “Hello World” application I promised in the title.

The first step is to create a new application. How do we do this? Well, that is ridiculously simple. Just add a new JavaScript file somewhere on your machine. In my case, I create a file called “HelloWorld.js”. Inside that JavaScript file, I add any functionality I need.

How you edit the JavaScript file is entirely up to you. With something as trivial as what we are building now, Notepad is good enough. But other options include Notepad++, Sublime, WebStorm, WebMatrix and even Visual Studio. But as I said, for now, Notepad is good enough…

So, the first trembling steps in Node development is to open the JavaScript file in Notepad and add the following line of code

console.log('Hello World');

Ok, that is a bit ridiculous as such, but it is a start! And as you probably figured out, it just writes “Hello World” to the console…

The next step is to run the application… To do this, start the “Node.js Command Prompt”, which was installed when installing Node. It is just a command prompt with Node paths added (I assume), enabling running node easily. Using good old “cd” statements, locate the directory containing the “HelloWorld.js” file. And then write “node HelloWorld.js” and press enter.

And voila, the console writes out “Hello World” like this…

image

Ok, so I admit…that is NOT impressive at all. Not looking at it at least… The fact that we can run JavaScript like this is kind of impressive and cool, but I guess we need something more to get seasoned developers excited… So let’s turn the application into a webserver and serve up our message using HTTP instead…

To be able to start a webserver, we need some way of opening a port and start listening and talking HTTP. Luckily, Node comes with that built in. However, it is defined in a separate “module”. Modules are basically pieces of code bundled into discrete “lumps” that we can use to build larger applications. Pretty much like assemblies in .NET. And just as with assemblies in .NET, we have to reference them in some way to be able to use them. In Node, this is done using a method called “require()”. Using this functionality, we can quickly acquire the functionality needed to create an HTTP server.

In this case, the module needed is called…wait for it…wait for it…http! Yes, the module is called http, and getting hold of it is done like this

var http = require('http');

Once we got a hold of the module we need, it is time to create whatever functionality we need. In this case, we want to return “Hello World” whenever someone makes a request.

Creating a new webserver is done by calling the method “createServer()” on the http module. The “createServer()” method takes a single parameter, a “callback function”, “lambda”, or in JavaScript, a function. The function takes 2 parameters, one to hold the information about the request, and one for the response. So in this case, the code needed looks like this

var http = require('http');
var server = http.createServer(function(req,res) {
res.end('Hello World');
});

Ok, that was pretty easy! However, creating the server is not enough. We have to start it as well, which is done using a method called “listen()”. It takes 1 parameter, the port to listen to. In my case, I will use 8080. Giving me some code that looks like this

var http = require('http');
var server = http.createServer(function(req,res) {
res.end('Hello World');
});
server.listen(8080);
console.log('Server running...listening on port 8080');

As you can see, I added a console.log at the end as well, to make it easier to see that it is running…

Now that the application is done, running it using the Node command prompt will result in a view like this

image

which REALLY isn’t impressive. However, note that it is just locked there… It doesn’t just return… If one opens a webbrowser and browse to http://localhost:8080/, it will actually render the following

image

Cool! That means that we have just created a fully fledged webserver in 5 lines of code. And it could really be compressed into even fewer if we wanted to.

But how do we stop it? Well, the ever useful Ctrl+C will stop the execution, and in this case the webserver.

To make it a little more interesting, it is not that hard to add some logging to each incoming request, and thus let us know what is happening in the server. Just adding a single log-line inside the server function like this

var server = http.createServer(function(req,res) {
console.log('Incoming request for ' + req.url);
res.end('Hello World');
});

will offer you a bit more on the server end to identify what is really happening in the server.

Making a few requests for some different paths with the logging in place, will generate an output like this

image

As you can see, the http-server will happily accept any path. So it is up to you to add some functionality to parse the path and querystring and so on.

Sidenote: The requests for favicon.ico is automatically added by the browser to present a little icon for the website. In most cases this isn’t something you reflect on, but having a “raw” server like this, you start realizing exactly how much work goes unnoticed when building on top of other frameworks…

Or, you could go even further and write out the WHOLE request object to see what it is all about. The console.log() method can take the whole object and print our every single property on it, which can be really helpful once in a while. So doing something like this

var http = require('http');
var server = http.createServer(function(req,res) {
console.log(req);
res.end('Hello World');
});
server.listen(8080);
console.log('Server running...listening on port 8080');

will write out the whole object for us, which can be really helpful for debugging purposes. It looks something like this

image

Luckily, you do not have to implement an HTTP server completely from scratch like this. There are pre-built ones that you can easily “plug in”. But that will be the topic for the next post I think…

Comments (1) -

Hi
Nice post. I have also been bitten by the Node.js bug. Here is my latest post about it, a review of Sams Tech Yourself Node.js in 24 Hours.  www.buzzfrog.se/.../

/dag

Add comment