A Node.js Primer

Moving into the second decade of the 21st century, if you have been immersed in the web development community — and more specifically, the JavaScript community — in any capacity, then you likely remember hearing something about Node.js discussed somewhere. Maybe you already know all about it, maybe you know a little, or maybe you’re not yet familiar with it. In what follows, we’re going to take a brief look at some of the components of Node.js, what it is, and why people have gotten excited about it.

Node.js Introduction

What is Node.js? Before we get into that, let’s back up a minute and start by talking about web servers. You know about web servers, right? They’re computers that have software running on them that are able to respond to HTTP requests from clients (which most of the time means browsers like Chrome, Firefox, Safari, and Internet Explorer… either desktop or mobile). They’re written in languages like Perl, C, and C++. Then they have other code like Python or PHP that runs on top of them so that when a client connects to a server, all the code runs, works it’s magic (hopefully in a semi-functional way) and returns a web page of HTML to the browser… or if the endpoint is a web service: XML or a JSON payload. This is a pretty standard interaction that occurs billions of times each day across the world. If you do anything on the Internet, you participate in this process most often without even thinking about what is going on behind the scenes in the client-server interaction.

So where does Node.js come into the picture? Basically Node.js is an implementation where, instead of responding to HTTP requests, processing them, and returning web pages using the aforementioned languages, you use JavaScript instead! Node.js becomes a web server written in JavaScript. And it doesn’t just stop there. You can also run Node.js right in your own desktop environment and use utilities to perform file processes and other tasks just as you could do if you were using an installed application that was written in Java or something else. So Node.js could perhaps be better described as “JavaScript running outside of the browser.” Local applications are definitely a very useful component of Node.js, but we’re going to specifically focus on the aspect of using Node.js as a web server. But I’d definitely recommend looking at a number of different utilities available for installation to see if you can use Node.js in your development processes or just as something that makes your life easier in some way.

So, if the real interesting thing about Node.js is that JavaScript runs on the server and returns web pages and you can program your own web server in JavaScript… why would you want to do that, you ask? After all, a lot of these web servers written in these other languages are really well established, have been around for years, and have been optimized for performance and reliability by a community of super-smart programmers who have been hammering away on these projects for what seems like forever. Why do I have to reinvent the wheel and write my own server software where I’ll likely make all kinds of mistakes and leave security holes open? These are definitely all valid concerns. The real trade-off is that, depending on the type of application you are developing, in some cases the performance possibilities and simplicity that Node.js offers are too good to pass up. And don’t fret. Fortunately there are modules out there — like Express, a web-application framework that runs on top of Node.js — that are fully functioning web servers that have great communities and lots of testing behind them! You don’t even have to write the web server yourself. You can just install it and beyond your way!

But again you may still be wondering why are people going to all this trouble. As it turns out there are some aspects of the JavaScript language that have certain advantages that other languages don’t. One of the big challenges for websites living on servers is handling many different requests coming into it at once. As traffic increases, performance often suffers resulting in slow loading web pages and a diminished user-experience (UX). You may have experienced this in your development career or just your everyday browsing experience (though high-traffic is not always the sole cause of slow websites). To “scale” with the increase in traffic a website’s server has to do something to handle it. One approach is to make use of multithreading which can be challenging to develop for. Another approach companies with high-traffic websites use is just to add a bunch more servers (which can also carry an increased cost of installation and maintenance). Node.js, however, because of the way that it is structured can handle many different concurrent connections and requests from clients because of JavaScript’s event-driven architecture and the ability to make use of callback functions that execute when a resource is ready. Thus, Node.js can get a request, say “Here’s the callback to call once everything ready” and then move on to handling the next request. As is summarized in the introduction to the book Node.js: Up and Running

JavaScript is an event-driven language, and Node uses this to its advantage to produce highly scalable servers. Using an architecture called an event loop, Node makes programming highly scalable servers both easy and safe. There are various strategies that are used to make servers performant. Node has chosen an architecture that performs very well but also reduces the complexity for the application developer. This is an extremely important feature. Programming concurrency is hard and fraught with danger. Node sidesteps this challenge while still offering impressive performance. As always, any approach still has trade-offs…

So Node.js is definitely not a silver-bullet, but it does offer some advantages that other environments may not have. Without getting too bogged down in the technical details, just know that Node.js is just something you can use to run your website like any other piece of software you might choose for various reasons. Hopefully, this will become a bit clearer as we move along. Having never programmed a web server myself, I sometimes don’t really know what the all the hype for Node.js is all about. But people much smarter than I say that it’s worth taking a look at.

Installing Node.js

To install Node.js on your machine it might be a bit different depending on what platform you are using. Head on over to the Node.js website to follow the instructions there for your platform. One thing I’d definitely recommend, you’d definitely want to have Node.js avaialble to be run from the command line globally so that you can run Node from the command-line anywhere. In Windows, this means adding it to your environment PATH (which is one of the options when using the installer).

After you have node installed, do a quick test to see that everything is working. Create a file called test.js and write the following code in the file…

console.log("Hello! Node.js is running...");

Then open your favorite terminal (I like BASH) in the same directory and type the following…

$ node test.js

If you see the text “Hello! Node.js is running…” displayed, Node.js is installed and you are good to go!

Obligatory “Hello World” in Node.js

Below is the obligatory “Hello World” example in Node.js. Recall that we said that that the interesting thing about Node.js is that we are running JavaScript on the server. Well, below is all the code that you need to create a functioning web server written in JavaScript using Node.js

var http = require('http');

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

console.log('Server running at https://127.0.0.1:8124/');

Now if you open a browser and type in https://127.0.0.1:8124/ you should see the text “Hello World” appear. Of course, this is not a very interesting server and it only has one route, but it shows how little code in JavaScript is needed to up and running with Node.js.

Installing Modules with NPM

Node.js uses the module pattern to load dependencies. This post on RequireJS and this post on JavaScript modules talk a bit more about what that is if you are not entirely familiar with the module pattern in JavaScript. In the previous section we loaded Node.js’s HTTP module with the following line of code…

var http = require('http');

You aren’t just limited to the modules that ship with Node. You can also use a utility called “npm” that is part of the Node.js installation (so you already have it installed because you have Node installed) to install other modules directly from your client using the command line. That’s another thing that people really like about Node.js: the community. There are many different helpful utilities that 3rd party developers have written for Node.js and posted them on npm where they can be installed and used freely by everybody. Sometimes people call the npm utility “Node Package Manager” or “Node Packaged Modules” though the npm website FAQ insists that this is not the case. Whatever you call it, it’s a useful tool. For example, to install Express — a 3rd party Node.js module that you can use to easily create web applications just as you would using something like Django, CodeIgniter, Laravel in Python or PHP — we just have to type the following into our command line…

$ npm install express

This will download all of the files that express requires and will place them in a folder called “node_modules”.

Then to use the express module in our Node.js files we just have to include it just as we did with our HTTP module. For example, the “Hello World” in Node.js example above couple be rewritten using Express to produce the same result…

var app = require('express');

app.get('/', function(request, response) {
   response.send("Hello World");
});

app.listen(8124);

If you need to install more than one module at once you can separate them by spaces…

$ npm install express socket.io grunt

Another way that you can install modules is to create a package.json file and put it in your project root. Then add the following…

{
    "name": "Node Primer",
    "description": "Node Primer by 9bit Studios...",
    "version": "0.0.1",
    "dependencies": {
        "express": "3.x"
    }
}

then all you have to do is type the following…

$ npm install

Node.js will look for the package.json file in the same directory and pull down all the dependencies you have specified and place them all in the node_modules folder!

The first few properties of the package.json file define some metadata, but the most important component is the dependencies. You can add more and more to this object (comma-separated), specify version numbers and by typing the above command to install everything that you need. For example, to add the module mongoose, you could edit the package.json as follows…

{
    "name": "Node Primer",
    "description": "Node Primer by 9bit Studios...",
    "version": "0.0.1",
    "dependencies": {
        "express": "3.x"
        "mongoose": "~3.5.5"
    }
}

And then just run npm install again. It’s that easy!

As mentioned previously, there are lots and lots and lots of modules available on the Node Package Manager Registry. Feel free to browse around to see if you can find anything that might be useful. Some of the more popular modules that people install include Grunt which is a JavaScript task-runner, socket.io which helps developers utilize web-sockets in JavaScript, and Mongoose which is a utility that focuses on easily integrating the NoSQL database MongoDB into your application. More info on Grunt can be found on the Grunt website. There many other modules available on npm for all sorts of different uses. You’ll just need to do a search for whatever is in line with your particular needs.

Obviously, we’ve just scratched the surface on some of the exciting and interesting aspects of Node.js. We’ve looked installation, installing modules, and how Node.js it can be used to create web applications on the server. That’s just the beginning. In upcoming discussions, we’ll look at some of the more advanced features of Node and how you can leverage some of the some of the more popular modules to use Node in whatever capacity you need it. Until next time…

, , , , 9bit Studios E-Books

Like this post? How about a share?

Stay Updated with the 9bit Studios Newsletter

1 Response to A Node.js Primer

  1. Nicanord says:

    thanks very much.

Leave a Reply

Your email address will not be published. Required fields are marked *