Making Server JavaScript Apps with Node.js

JavaScript used to be used only within the browser. But nowadays JavaScript can be used pretty much anywhere programming is supported. It can be used in a browser, server, mobile device, and even desktop.

I’m going to write about building JavaScript applications for mobile devices and desktops in future posts. Today I will discuss how to make server applications in JavaScript.

Skip to the Code

What is Node.js?

What the browser is for client side JavaScript, Node.js is for server side JavaScript. Simply put, Node.js is a runtime environment for JavaScript designed to build server applications.

In 2009 Ryan Dahl decided that he wanted to write JavaScript on the server. At the time Chrome was only a year old, but parts of it had been open sourced by Google into a project called Chromium. Part of that project was an engine that ran JavaScript called V8.

Because Chromium was open sourced Dahl was able to pull out the V8 engine and decouple it from the browser, effectively creating a way of running JavaScript without a browser.

How is it Different From JavaScript and Other Server Side Languages

Node.js is run on a server by you, the developer. Unlike browser based JavaScript you don’t have to worry about malicious code being run on your server because you’re writing the code. You have don’t have to worry about a user being able to inject their own code onto your server, after all its your server, which they don’t have access to.

This means Node.js is not going to be sandboxed the same way browser JavaScript is, which gives Node.js access to the core components of the computer it’s running on. Again, unlike browser based JavaScript it can access the file system, read processor information, and open servers on various ports.

Advantages and Disadvantages

JavaScript without a browser has some advantages and some disadvantages and some that that are in the grey area.

One advantage is there is no need to have global objects anymore. There is no window, no mouse, and no direct user interaction, and thus no need for the document, location, navigator, and many other objects. Furthermore the entire window object isn’t needed. But when Node.js was being created this caused a problem initially. If there was no window object what would variables be attached to when they were declared?

The solution was to create a new object called global.

One advantage/disadvantage that is in the grey area is the fact that JavaScript is an asynchronous language. To explain this I will first explain how PHP runs.

In PHP you may interact with a database, read data, write data, and then present that data on an HTML page. You expect these things to happen in order, connect to the database, read the data, write the data, and finally render the HTML. You expect this because it’s how PHP works. PHP stops the execution of any other PHP code on the server until it’s current operation is complete. This is called a blocking, synchronous langauge. It makes code easy to write but it makes it very slow.

Node.js is an asynchronous language. Anything that will require an indefinite amount of time to complete, like writing a file to the hard drive, or reading from a database, is told to report back when it’s done. Node.js then keeps running code, and waits for the complex task to complete. When it does it runs a function written by the developer to handle the completion of that task. This is called a callback function.

Writing code like this can at first be confusing, but asynchronous languages are much much faster than synchronous languages. They can server multiple users at the same time. They can also hold open connects to a single user, which makes them idea for WebSockets, which I have talked about a lot before.

AJAX vs WebSockets
The Good and Bad of WebSockets Over AJAX

Managing Libraries

In standard JavaScript, libraries are imported using the tag. But, again, in Node.js there is no window and no document, and thus no way to import the library the standard way. A new way had to be created. Instead of importing with the tag a new global function and specification was created for defining libraries. The function is called require and it uses a specification called CommonJS.

To sum up the differences, take all the browser specific things you know about JavaScript and delete them. Replace them with new objects and new functions that are specific to servers. Leave the core JavaScript syntax the same and you have Node.js.

What is NPM

As I said above Node.js libraries are written using a specification called CommonJS and thus can only be used within the Node.js runtime (basically).

After Node.js started gaining a developer community it quickly became obvious that Node.js need a way for developers to share their libraries. They also needed a way to automatically install libraries into their Node.js server. Other systems like RubyGems and Python’s PIP had already existed, so these were looked at for inspiration.

What was created was called NPM by it’s creator, Isaac Z. Schlueter.

NPM allows a developer to create a JSON document containing a list of all required libraries needed for a project. NPM can then automatically install those libraries.

Here is an example of such a file, which is always called package.json.

{
	"name": "testing-application",
	"version": "0.0.1",
	"authors": [
		{
			"name": "Alan James",
			"email": "alanjames1987@gmail.com"
		}
	],
	"dependencies": {
		"annyang": "1.0.1",
		"express": "3.4.7"
	}
}

This file will download two libraries, annyang, and express.

Let’s Finally Get to Coding

Start by downloading Node.js from http://nodejs.org/ for your system. This will also come with NPM.

After you have done that we will start creating a Node.js server. To start create a file called app.js in the same folder as your package.json. In this file we will first import the libraries we just downloaded and use them to create a server. In other tutorials you may see this file called server.js. These are the two most common ways of naming it, but it’s name honestly doesn’t matter as long as it makes sense to you.

Annyany is a library for initiating callback functions based on keywords and express is a framework uses for routing requests based on a URL. So, I will be using express, and not annyang, in this example to create a server. I just wanted to show how multiple libraries can be specified in a single package.json file.

In order to use express I have to import it with the require statement. I can then save that imported library to a variable, which effectively becomes a reference to the express library, which in reality returned a function.

var express = require('express');

I can call this function to create a new express server

var express = require('express');
var app = express();

And I can setup a route for express to serve.

app.get('/', function(req, res){
  res.send('hello world');
});

Finally I can tell express to start listening on port 3000.

app.listen(3000);

Your entire application should now look like this.

var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.send('hello world');
});

app.listen(3000);

To start this server we first need to install the libraries it requires.

Navigate to your project directory in terminal. Once there run this command.

npm install

NPM will then scan your package.json and determine what libraries need to be installed.

We can then start the server with this command.

node app.js

Your terminal will do nothing that looks useful at all, but that means your server is running.

In a browser go to localhost:3000. You should get “hello world” output on the screen.

This is how to setup a basic Node.js server. In the future I will cover how to start creating a more complex server.

Demo Repo

Making Server JavaScript Apps with Node.js