Node.js is a server platform built on Google Chrome’s JavaScript runtime. It has an event-driven, non-blocking I/O model so it’s a fast and efficient as you could want. It’s also probably a good glimpse into the future of server technology.
With the server running pure JavaScript, it’s a great plaform for development of JavaScript-centric applications. Using the same object across the client and server saves a lot of time and effort in wrapping up objects for transport.
Anyway, if you’re reading this, then you probably have a good idea of what Node is and why you’d want to use it. So, let’s get started.
Install Node
Node is pretty easy to get on your system. Go grab the installer and install that. Done? Easy? Okay, next.
Let’s write a server…
…without writing any code.
Rather than create a server from scratch, we’re going to use the Express Framework. This will give us a good basis from where to start.
Create new folder for your project. Open up a command terminal and navigate to there.
Node ships with a pakcage manager (NPM) than can be used to pull down all sorts of packages from the main repository. We’ll use this to get express. So, install it:
You should see a bunch of get requests pulling down the required packages. Something like this:
Now we have Express, let’s create our application. The basic command for this is just express but we’re going to use a couple of the command switches to tell it to enable session support and to use Less as the CSS engine. So, use this command:
You’ll likely get a message telling you that the directory isn’t empty and asking if you want to continue. This is just because we have the node_modules folder in there (where Express was downloaded to) so isn’t going to be an issue. Say yes (y).
If all goes well, you’ll see something similar to:
Express has usefully listed our next two steps for us. We need to install dependencies and then run our app.
The npm install command uses the package.json file in our application root to pull down and packages that are listed in there. So, run that:
Express will have pulled down all of the required packages for its use:
Then, all we have left to do is run the app:
You should get a confirmation message that your application is up and running (it defaults to port 3000):
Open up a browser and check that you have your app at localhost:3000. You should get something like in the following:
Underwhelming but we’re just getting started.
Not the most exciting of beginning but we’ve created a full application in Node with just the commands:
In part 2, we’ll take a closer look at what we’ve created.