An Introduction to Node.js for Front-End Developers

I’m going to assume if you’re reading this article that you’re a front-end developer that uses JavaScript on a daily basis. You’re probably very comfortable with libraries like jQuery, YUI3, Backbone or AngularJS. If this is the case then transitioning to Node.js really won’t be that challenging. I know you’re probably thinking “But Node.js and backend coding sound scary.”

Well, I’ve got a secret for you, it’s all just JavaScript. So it’s really not that scary because it’s something you already use all of the time. So, now that you’ve gotten past the jitters, lets jump right in!

nodejs.org logo

First Things First

Our first step is to install Node.js. Head over to nodejs.org and install the correct version for your platform. Luckily they have installers for Windows and Mac. If your on linux (Ubuntu) you should be able to open a terminal and run sudo apt-get update and then sudo apt-get install node.

Setting up our Project

Lets quickly setup a sample project that we can use throughout this tutorial. Somewhere on your machine, create a folder named node-test, I’m on a Mac, so I put it under ~/Sites/nodejs/node-test.

The Package Manager

My favorite part about Node.js is the node package manager or npm for short. What’s really great about npm is that it allows you to define all of your 3rd party libraries in one file. In our node-test folder, lets create a file called package.json and paste the following code in to it:

{
  "name": "node-test",
  "version": "0.0.1",
  "description": "a simple node.js project",
  "private": true,
  "dependencies": {
    "express": "3.x"
  }
}

Now, this a very simplified version of this file and you can and should add more options for your own project.

The first thing you’ll notice is that we’ve defined a name, version and description for our project. You can change these to whatever values you’d like. Next we set private to be true because this is just a test project for the purposes of this tutorial. The most important part of this file is the dependencies attribute. This is where we define all of our third party packages. You’ll notice the only thing we have defined so far is Express.js which, according to their site is a “web application framework for node”. A simple analogy might be that node is like plain JavaScript and express is like jQuery. You can write plain JS all you want, but using jQuery makes your life a lot easier, and the same applies for node and express.

The only thing left to do before we start setting up our project is open up a terminal, cd into your node-test directory and run npm install. If everything went smoothly you should see something like this:

~/Sites/nodejs/node-test  $ npm install
npm http GET https://registry.npmjs.org/express
...
express@3.4.3 node_modules/express
├── methods@0.0.1
├── cookie-signature@1.0.1
...
└── connect@2.10.1 (uid2@0.0.2, pause@0.0.1, qs@0.6.5, bytes@0.2.0, raw-body@0.0.3, negotiator@0.2.8, multiparty@2.2.0)
Setting up your project

Okay, now that we have all of our dependencies installed, lets actually do something fun. In our node-test directory create an new file named app.js. For this project all of our node specific code is going to live in this one file.

Open up app.js in your favorite editor (I like Sublime) and paste this code in to get us started.

var express = require('express'),
    path = require('path');

//create our express app
var app = express();

//add some standard express middleware
app.configure(function() {
    app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.static('static'));
});

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

//have our app listen on port 3000
app.listen(3000);
console.log('Your app is now running at: http://127.0.0.1:3000/');

Now, lets break this down line by line.

You’ll notice something interesting on the first line. We’re importing express.js. Node uses modules, and a really good example of this is express.js. To demonstrate the point even further, lets take a look at a simple example:

//in a file bar.js
exports.bar = function() {
  return 'Hello World Foo Bar'
};

//in app.js
var foo = require('./bar.js');
foo.bar(); //prints 'Hello World Foo Bar' to the console.

In the above code we require bar.js and assign it to the foo variable. Then we call the bar method defined in bar.js. Once you understand how this works, node becomes a lot simpler.

So, getting back to our app.js file you’ll see we import express and path and assign them both to variables to be used later. The next thing we do is setup our express app, which is straight out of the express documentation. Then we add some standard express middleware.

Now the fun part, we define our first route. You’ll notice that we’re using app.get here which defines that we want this to be a GET request. Express makes it very easy to create RESTful API’s, so you could also use app.post to create, app.put to update and app.del to delete.

In the next part of this line we are defining the url. For this example we are using the root of the domain '/', but we could also use something like '/hello-world'.

We then pass in an anonymous callback function function(req, res) { which gets executed when a url matches the route we just defined. Two arguments are passed to the callback, req and res. An easy way to think about this, is req is everything that’s coming from the browser and res is everything we want to send back to the browser. Express has a lot of nifty shortcuts or helper methods to make our life easier and res.send is one of them. Here you can see we are saying take this string 'hello world' and send it back to the browser for the everyone to see.

Finally we are telling our app to run on port 3000. You can pick any port you want, as long as something else isn’t using it.

So, are you ready to see this in action? Alright, open your terminal back up and from our node-test directory run node app.js. Then in your browser go to http://127.0.0.1:3000/ and you should see 'hello world' printed out on the screen. Pretty neat right?

Now that you’ve got the basics down, the flood gates are wide open. You can literally setup a dynamic website in minutes.

Extending our example

Sending text to the browser is fun, but in the real world we want to send a styled HTML document for our sites visitors to see. In our node-test directory create a new directory named views. Inside of views create an index.hbs file, which will hold the HTML for our sites new home page. In index.hbs we can add some default html (I got this from one of the Twitter Bootstrap examples):

<html>
	    <head>
	      <title>Node Text</title>
	      <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
	    </head>
	    <body>
	      <div class="navbar navbar-inverse navbar-fixed-top">
	          <div class="container">
	            <div class="navbar-header">
	              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
	                <span class="icon-bar"></span>
	                <span class="icon-bar"></span>
	                <span class="icon-bar"></span>
	              </button>
	              <a class="navbar-brand" href="/">Node test</a>
	            </div>
	            <div class="collapse navbar-collapse">
	              <ul class="nav navbar-nav">
	                <li class="active"><a href="/">Home</a></li>
	              </ul>
	            </div>
	          </div>
	        </div>

	        <div class="container">

	          <div class="starter-template" style="padding-top: 50px;">
	            <h1>Hello World</h1>
	            <p class="lead">Use this document as a way to quickly start any new project.<br> All you get is this text and a mostly barebones HTML document.</p>
	          </div>

	        </div>
	    </body>
	    </html>

In order for our app to handle templating, we need to do a couple of things. First in app.js right above where we define our middleware add these two lines:

//setup our app to use handlebars.js for templating
app.set('view engine', 'hbs');
app.set('views', path.join(__dirname, 'views'));

This tells express that we want to use handlebars.js for templating.

While were in app.js change this line from res.send('hello world'); to res.render('index');. This change tells express to go look in the views directory for a file named index.hbs.

The next thing we need to do is to open our packages.json folder back up and add the following line: "hbs": "*", under "express": "3.x",. Then go back to your terminal and re-run the npm install command. Now that you’ve got that installed, restart the server by running node app.js in the terminal and open your browser to http://127.0.0.1:3000/. You should see a nice new responsive home page for your site.

Where to go from here?

I would highly recommend reading the express.js guide and API documentation. Both are short reads and will teach you a lot.

Node has a great community and the 3rd party libraries are amazing. Chances are if you want it, someones already written it for you. Start by searching through npmjs.org, but Google and Github are also great resources.

You might decide that your shinny new site needs a database. Well node works really well with MongoDB, which is great for front-end developers because it uses json to store data. I would recommend looking into mongoose.js which makes working with MongoDB even easier.

Author: (1 Posts)

Nathan Smith is the proprietor of Jobety, a once a week, free newsletter with handpicked Web Design, Development and Freelance jobs.

Comments