7 min read

(For more resources related to this topic, see here.)

Setting up the application

Every application has to be set up, so we’ll begin with that. Create a folder for your project—I’ll call mine simpleBlog—and inside that, create a file named package.json. If you’ve used Node.js before, you know that the package.json file describes the project; lists the project home page, repository, and other links; and (most importantly for us) outlines the dependencies for the application.

Here’s what the package.json file looks like:

{ "name": "simple-blog", "description": "This is a simple blog.", "version": "0.1.0", "scripts": { "start": "nodemon server.js" }, "dependencies": { "express": "3.x.x", "ejs" : "~0.8.4", "bourne" : "0.3" }, "devDependencies": { "nodemon": "latest" } }

This is a pretty bare-bones package.json file, but it has all the important bits. The name, description, and version properties should be self-explanatory. The dependencies object lists all the npm packages that this project needs to run: the key is the name of the package and the value is the version. Since we’re building an ExpressJS backend, we’ll need the express package. The ejs package is for our server-side templates and bourne is our database (more on this one later).

The devDependencies property is similar to the dependencies property, except that these packages are only required for someone working on the project. They aren’t required to just use the project. For example, a build tool and its components, such as Grunt, would be development dependencies. We want to use a package called nodemon. This package is really handy when building a Node.js backend: we can have a command line that runs the nodemon server.js command in the background while we edit server.js in our editor. The nodemon package will restart the server whenever we save changes to the file. The only problem with this is that we can’t actually run the nodemon server.js command on the command line, because we’re going to install nodemon as a local package and not a global process. This is where the scripts property in our package.json file comes in: we can write simple script, almost like a command-line alias, to start nodemon for us. As you can see, we’re creating a script called start, and it runs nodemon server.js. On the command line, we can run npm start; npm knows where to find the nodemon binary and can start it for us.

So, now that we have a package.json file, we can install the dependencies we’ve just listed. On the command line, change to the current directory to the project directory, and run the following command:

npm install

You’ll see that all the necessary packages will be installed. Now we’re ready to begin writing the code.

Starting with the server

I know you’re probably eager to get started with the actual Backbone code, but it makes more sense for us to start with the server code. Remember, good Backbone apps will have strong server-side components, so we can’t ignore the backend completely.

We’ll begin by creating a server.js file in our project directory. Here’s how that begins:

var express = require('express'); var path = require('path'); var Bourne = require("bourne");

If you’ve used Node.js, you know that the require function can be used to load Node.js components (path) or npm packages (express and bourne). Now that we have these packages in our application, we can begin using them as follows:

var app = express(); var posts = new Bourne("simpleBlogPosts.json"); var comments = new Bourne("simpleBlogComments.json");

The first variable here is app. This is our basic Express application object, which we get when we call the express function. We’ll be using it a lot in this file.

Next, we’ll create two Bourne objects. As I said earlier, Bourne is the database we’ll use in our projects in this article. This is a simple database that I wrote specifically for this article. To keep the server side as simple as possible, I wanted to use a document-oriented database system, but I wanted something serverless (for example, SQLite), so you didn’t have to run both an application server and a database server. What I came up with, Bourne, is a small package that reads from and writes to a JSON file; the path to that JSON file is the parameter we pass to the constructor function. It’s definitely not good for anything bigger than a small learning project, but it should be perfect for this article. In the real world, you can use one of the excellent document-oriented databases. I recommend MongoDB: it’s really easy to get started with, and has a very natural API. Bourne isn’t a drop-in replacement for MongoDB, but it’s very similar. You can check out the simple documentation for Bourne at https://github.com/andrew8088/bourne.

So, as you can see here, we need two databases: one for our blog posts and one for comments (unlike most databases, Bourne has only one table or collection per database, hence the need for two).

The next step is to write a little configuration for our application:

app.configure(function(){ app.use(express.json()); app.use(express.static(path.join(__dirname, 'public'))); });

This is a very minimal configuration for an Express app, but it’s enough for our usage here. We’re adding two layers of middleware to our application; they are “mini-programs” that the HTTP requests that come to our application will run through before getting to our custom functions (which we have yet to write). We add two layers here: the first is express.json(), which parses the JSON requests bodies that Backbone will send to the server; the second is express.static(), which will statically serve files from the path given as a parameter. This allows us to serve the client-side JavaScript files, CSS files, and images from the public folder.

You’ll notice that both these middleware pieces are passed to app.use(), which is the method we call to choose to use these pieces.

You’ll notice that we’re using the path.join() method to create the path to our public assets folder, instead of just doing __dirname and ‘public’. This is because Microsoft Windows requires the separating slashes to be backslashes. The path.join() method will get it right for whatever operating system the code is running on. Oh, and __dirname (two underscores at the beginning) is just a variable for the path to the directory this script is in.

The next step is to create a route method:

app.get('/*', function (req, res) { res.render("index.ejs"); });

In Express, we can create a route calling a method on the app that corresponds to the desired HTTP verb (get, post, put, and delete). Here, we’re calling app.get() and we pass two parameters to it. The first is the route; it’s the portion of the URL that will come after your domain name. In our case, we’re using an asterisk, which is a catchall; it will match any route that begins with a forward slash (which will be all routes). This will match every GET request made to our application. If an HTTP request matches the route, then a function, which is the second parameter, will be called.

This function takes two parameters; the first is the request object from the client and the second is the response object that we’ll use to send our response back. These are often abbreviated to req and res, but that’s just a convention, you could call them whatever you want.

So, we’re going to use the res.render method, which will render a server-side template. Right now, we’re passing a single parameter: the path to the template file. Actually, it’s only part of the path, because Express assumes by default that templates are kept in a directory named views, a convention we’ll be using. Express can guess the template package to use based on the file extension; that’s why we don’t have to select EJS as the template engine anywhere. If we had values that we want to interpolate into our template, we would pass a JavaScript object as the second parameter. We’ll come back and do this a little later.

Finally, we can start up our application; I’ll choose to use the port 3000:

app.listen(3000);

We’ll be adding a lot more to our server.js file later, but this is what we’ll start with. Actually, at this point, you can run npm start on the command line and open up http://localhost:3000 in a browser. You’ll get an error because we haven’t made the view template file yet, but you can see that our server is working.


Subscribe to the weekly Packt Hub newsletter

* indicates required

LEAVE A REPLY

Please enter your comment!
Please enter your name here