Chapter 3. Creating and setting up a MEAN project

This chapter covers

  • Managing dependencies by using a package.json file
  • Creating and configuring Express projects
  • Setting up an MVC environment
  • Adding Twitter Bootstrap for layout
  • Publishing to a live URL and using Git and Heroku

Now we’re really ready to get underway, and in this chapter we’ll get going on building our application. Remember from chapters 1 and 2 that throughout this book we’re going to build an application called Loc8r. This is going to be a location-aware web application that will display listings near users and invite people to login and leave reviews.

In the MEAN stack Express is the Node web application framework. Together Node and Express underpin the entire stack, so let’s start here. In terms of building up the application architecture, figure 3.1 shows where we’ll be focusing in this chapter. We’ll be doing two things:

Figure 3.1. Creating the encapsulating Express application, and starting to set up the main Express application

Getting the source code

The source code for this application is on GitHub at github.com/simonholmes/getting-MEAN. Each chapter with a significant update will have its own branch. I encourage you to build it up from scratch, through the course of the book, but if you wish you can get the code we’ll be building throughout this chapter from GitHub on the chapter-03 branch. In a fresh folder in terminal the following two commands will clone it, if you already have Git installed:

$ git clone -b chapter-03 https://github.com/simonholmes/getting-MEAN.git

This will give you a copy of the code that’s stored on GitHub. To run the application you’ll need to install some dependencies with the following commands:

$ cd getting-MEAN
$ npm install

Don’t worry if some of this doesn’t make sense just yet, or if some of the commands aren’t working. During this chapter we’ll install these technologies as we go.

  1. Creating the project and encapsulating the Express application that will house everything else except the database
  2. Setting up the main Express application

We’ll start with a bit of groundwork by looking at Express and seeing how we can manage dependencies and modules using npm and a package.json file. We’ll need this background knowledge to get going and set up an Express project.

Before we can really do anything we’ll make sure that you have everything you need installed on your machine. When that’s all done we’ll look at creating new Express projects from the command line, and the various options we can specify at this point.

Express is great, but you can make it better—and get to know it better—by tinkering a little and changing some things around. This ties into a quick look at model-view-controller (MVC) architecture. Here’s where we’ll get under the hood of Express a little, and see what it’s doing by modifying it to have a very clear MVC setup.

When the framework of Express is set up as we want it, we’ll next include Twitter’s Bootstrap framework, and make the site responsive by updating the Jade templates. In the final step of this chapter we’ll push the modified, responsive MVC Express application to a live URL using Heroku and Git.

3.1. A brief look at Express, Node, and npm

As mentioned before, Express is a web application framework for Node. In basic terms, an Express application is simply a Node application that happens to use Express as the framework. Remember from chapter 1 that npm is a package manager that gets installed when you install Node, which gives you the ability to download Node modules or packages to extend the functionality of your application.

But how do these things work together, and how do you use them? A key piece to understanding this puzzle is the package.json file.

3.1.1. Defining packages with package.json

In every Node application there should be a file in the root folder of the application called package.json. This file can contain various metadata about a project, including the packages that it depends on to run. The following listing shows an example package.json file that you might find in the root of a new Express project.

Listing 3.1. Example package.json file in a new Express project

This is the file in its entirety, so it’s not particularly complex. There’s various metadata at the top of the file followed by the dependencies section. In this default installation of an Express project there are quite a few dependencies. Express itself is modular so that you can add in components or upgrade them individually.

Working with dependency versions in package.json

Alongside the name of each dependency is the version number that the application is going to use. Notice that they’re all prefixed with a ~.

Let’s take a look at the dependency definition for Express 4.9.0. It specifies a particular version at three levels:

  • Major version (4)
  • Minor version (9)
  • Patch version (0)

Prefixing the whole version number with a ~ is like replacing the patch version with a wildcard, which means that the application will use the latest patch version available. This is considered best practice, as patches should only contain fixes that won’t have any impact on the application. But different major and minor versions could well include changes that cause problems with the application, so you want to avoid automatically using later versions of these.

3.1.2. Installing Node dependencies with npm

Any Node application or module can have dependencies defined in a package.json file. Installing them is really easy, and is done in the same way regardless of the application or module.

Using a terminal prompt in the same folder as the package.json file you simply need to run the following command:

$ npm install

This tells npm to install all of the dependencies listed in the package.json file. When you run it, npm will download all of the packages listed as dependencies and install them into a specific folder in the application called node_modules. Figure 3.2 illustrates the three key parts.

Figure 3.2. The npm modules defined in a package.json file are downloaded and installed into the application’s node_modules folder when you run the npm install terminal command.

npm will install each package into its own subfolder because each one is effectively a Node package in its own right. As such, each package also has its own package.json file defining the metadata including the specific dependencies. It’s quite common for a package to have its own node_modules folder. You don’t need to worry about manually installing all of the nested dependencies though, because this is all handled by the original npm install command.

Adding more packages to an existing project

You’re unlikely to have the full list of dependencies for a project right from the outset. It’s far more likely that you’ll start off with a few key ones that you know you’ll need, and perhaps some that you always use in your workflow.

Using npm, it’s really easy to add more packages to the application whenever you want. You simply find the name of the package you want to install and open a command prompt in the same folder as the package.json file. You then run a simple command like this:

$ npm install --save package-name

With this command npm will download and install the new package into the node_modules folder. The --save flag tells npm to add this package to the list of dependencies in the package.json file.

Updating packages to later versions

The only time npm downloads and reinstalls existing packages is when you’re upgrading to a new version. When you run npm install, npm will go through all of the dependencies and check the following:

  • The version defined in the package.json file
  • The latest patch version on npm (assuming you used the ~)
  • The version installed in the node_modules folder (if at all)

If your installed version is different from the definition in the package.json file, npm will download and install the version defined in package.json. Similarly, if you’re using a patch wildcard and there’s a later patch version available, npm will download and install it in place of the previous version.

With that knowledge under your belt, we can start creating our first Express project.

3.2. Creating an Express project

All journeys must have a starting point, which for building a MEAN application is to create a new Express project. To create an Express project you’ll need to have five key things installed on your development machine:

  • Node and npm
  • The Express generator installed globally
  • Git
  • Heroku
  • New command-line interface (CLI) or terminal

3.2.1. Installing the pieces

If you don’t have Node, npm, or the Express generator installed yet, see appendix A for instructions and pointers to online resources. They can all be installed on Windows, Mac OS X, and most mainstream Linux distributions.

By the end of this chapter we’ll also have used Git to manage the source control of our Loc8r application, and pushed it to a live URL using Heroku. Please take a look through appendix B, which guides you through setting up Git and Heroku.

Depending on your operating system you may need to install a new CLI or terminal. See appendix B to find out if this applies to you or not.

Note

Throughout this book I’ll often refer to the CLI as terminal. So when I say “run this command in terminal,” simply run it in whichever CLI you’re using. When terminal commands are included as code snippets throughout this book, they’ll start with a $. You shouldn’t type this into terminal; it’s simply there to denote that this is a command-line statement. For example, using the echo command $ echo 'Welcome to Getting MEAN', you’d just type in echo 'Welcome to Getting MEAN'.

Verifying the installations

To create a new Express project you must have Node and npm installed, and also have the Express generator installed globally. You can verify this by checking for the version numbers in the terminal using the following commands:

$ node --version
$ npm --version
$ express --version

Each of these commands should output a version number to terminal. If one of them fails, head back to appendix A on how to install it again.

3.2.2. Creating a project folder

Assuming all is good, let’s start by creating a new folder on your machine called loc8r. This can be on your desktop, in your documents, in a Dropbox folder—it doesn’t really matter, as long as you have full read and write access rights to the folder.

I personally do a lot of my MEAN development in Dropbox folders so that it’s immediately backed up and accessible on any of my machines. If you’re in a corporate environment this may not be suitable for you, so create the folder wherever you think best.

3.2.3. Configuring an Express installation

An Express project is installed from the command line, and the configuration is passed in using parameters on the command that you use. If you’re not familiar with using the command line, don’t worry, none of what we’ll go through in the book is particularly complex, and it’s all pretty easy to remember. Once you’ve started using it you’ll probably start to love how it makes some operations so fast!

For example—don’t do this just yet—you can install Express into a folder with a simple command:

$ express

This would install the framework with default settings into your current folder. This is probably a good start, but let’s take a look at some configuration options first.

Configuration options when creating an Express project

What can you configure when creating an Express project? When creating an Express project in this way, you can specify the following:

  • Which HTML template engine to use
  • Which CSS preprocessor to use
  • Whether to add support for sessions

A default installation will use the Jade template engine, but it will have no CSS preprocessing or session support. You can specify a few different options as laid out in table 3.1.

Table 3.1. Command-line configuration options when creating a new Express project

Configuration command

Effect

--css less|stylus Adds a CSS preprocessor to your project, either Less or Stylus, depending on which you type in the command.
--ejs Changes the HTML template engine from Jade to EJS.
--jshtml Changes the HTML template engine from Jade to JsHtml.
--hogan Changes the HTML template engine from Jade to Hogan.

For example—and this isn’t what we’re going to do here—if you want to create a project that uses the Less CSS preprocessor and the Hogan template engine you’d run the following command in terminal:

$ express --css less --hogan

To keep things simple in our project we won’t use CSS preprocessing, so we can stick with the default of plain CSS. But we do need to use a template engine, so let’s take a quick look at the options.

Different template engines

When using Express in this way there are four template options available: Jade, EJS, JsHtml, and Hogan. The basic workflow of a template engine is that you create the HTML template, including placeholders for data, and then pass it some data. The engine will then compile the two together to create the final HTML markup that the browser will receive.

All of the engines have their own merits and quirks, and if you already have a preferred one then that’s fine. In this book we’re going to be using Jade. Jade is very powerful and provides all of the functionality we’re going to need. As it’s the default template engine in Express you’ll also find that most examples and projects online use it, so it’s very helpful to be familiar with it. Finally, Jade’s minimal style makes it ideal for code samples in a book!

A quick look at Jade

Jade is unusual when compared to the other template engines in that it doesn’t actually contain HTML tags in the templates. Instead, Jade takes a rather minimalist approach, using tag names, indentation, and a CSS-inspired reference method to define the structure of the HTML. The exception to this is the <div> tag. Because it’s so common, if the tag name is omitted from the template, Jade will assume that you want a <div>.

Tip

Jade templates must be indented using spaces, not tabs.

The following code snippet shows a simple example of a Jade template and the compiled output:

From the first lines of the input and output you should be able to see that

  • With no tag name specified, a <div> is created.
  • #banner in Jade becomes id="banner" in HTML.
  • .page-header in Jade becomes class="page-header" in HTML.

So with that starting knowledge behind us, it’s time for us to create a project.

3.2.4. Creating an Express project and trying it out

So we know the basic command for creating an Express project, and have decided to use the default configuration options, so let’s go ahead and create a new project. In section 3.2.2 you should have created a new folder called loc8r. Navigate to this folder in your terminal, and run the following command:

$ express

This will create a bunch of folders and files inside the loc8r folder that will form the basis of our Loc8r application. But we’re not quite ready yet. Next you’ll need to install the dependencies. As you may remember, this is simply done by running the following command from a terminal prompt in the same folder as the package.json file:

$ npm install

As soon as you run it you’ll see your terminal window light up with all of the things it’s downloading. Once it has finished, the application is ready for a test drive.

Trying it out

Running the application is a piece of cake. We’ll take a look at a better way of doing this in just a moment, but if you’re impatient like me, you’ll want to see that what you’ve done so far works.

In terminal, in the loc8r folder, run the following command:

$ npm start

You should see a confirmation similar to this:

[email protected] start /path/to/your/application/folder

This means that the Express application is running! You can see it in action by opening a browser and heading over to localhost:3000. Hopefully you’ll see something like the screenshot in figure 3.3.

Figure 3.3. Landing page for a barebones Express project

Admittedly, this is not exactly ground-breaking stuff right now, but getting the Express application up and running to the point of working in a browser was pretty easy, right?

If you head back to terminal now you should see a couple of log statements confirming that the page has been requested, and that a stylesheet has been requested. To get to know Express a little better, let’s take a look at what’s going on here.

How Express handles the requests

The default Express landing page is pretty simple. There’s a small amount of HTML, of which some of the text content is pushed as data by the Express route. There’s also a CSS file. The logs in terminal should confirm that this is what Express has had requested and has returned to the browser. But how does it do it?

About Express middleware

In the middle of the app.js file there are a bunch of lines that start with app.use. These are known as middleware. When a request comes in to the application it passes through each piece of middleware in turn. Each piece of middleware may or may not do something with the request, but it’s always passed on to the next one until it reaches the application logic itself, which returns a response.

Take app.use(express.cookieParser()); for example. This will take an incoming request, parse out any of the cookie information, and then attach the data to the request in a way that makes it easy to reference it in the controller code.

You don’t really need to know what each piece does right now, but you may well find yourself adding to this list as you build out applications.

All requests to the Express server run through the middleware defined in the app.js file (see the sidebar “About Express middleware”). As well as doing other things, there’s a default piece of middleware that looks for paths to static files. When the middleware matches the path against a file, Express will return this asynchronously, ensuring that the Node.js process isn’t tied up with this operation and therefore blocking other operations. When a request runs through all of the middleware, Express will then attempt to match the path of the request against a defined route. We’ll get into this in a bit more detail later in this chapter.

Figure 3.4 illustrates this flow, using the example of the default Express homepage from figure 3.3.

Figure 3.4. The key interactions and processes that Express goes through when responding to the request for the default landing page. The HTML page is processed by Node to compile data and a view template, and the CSS file is served asynchronously from a static folder.

The flow in figure 3.4 shows the separate requests made and how Express handles them differently. Both requests run through the middleware as a first action, but the outcomes are very different.

3.2.5. Restarting the application

A Node application compiles before running, so if you make changes to the application code while it’s running, they won’t be picked up until the Node process is stopped and restarted. Note that this is only true for application code; Jade templates, CSS files, and client-side JavaScript can all be updated on-the-fly.

Restarting the Node process is a two-step procedure. First you have to stop the running process. You do this in terminal by pressing Ctrl-C. Then you have to start the process again in terminal using the same command as before: npm start.

This doesn’t sound problematic, but when you’re actively developing and testing an application, having to do these two steps every time you want to check an update actually becomes quite frustrating. Fortunately there’s a better way.

Automatically restarting the application with nodemon

There are some services out there that have been developed to monitor application code that will restart the process when it detects that changes have been made. One such service, and the one we’ll be using in this book, is nodemon. nodemon simply wraps the Node application, and other than monitoring for changes causes no interference.

To use nodemon you start off by installing it globally, much like you did with Express. This is done using npm in terminal:

$ npm install -g nodemon

When the installation has finished, you’ll be able to use nodemon wherever you wish. Using it’s really simple. Instead of typing node to start the application, you type nodemon. So, making sure you’re in the loc8r folder in terminal—and that you’ve stopped the Node process if it’s still running—enter the following command:

$ nodemon

You should see that a few extra lines are output to terminal confirming that nodemon is running, and that it has started node./bin/www. If you head back over to your browser and refresh, you should see that the application is still there.

Note

nodemon is only intended for easing the development process in your development environment, and shouldn’t really be used in a live production environment.

3.3. Modifying Express for MVC

First off, what is MVC architecture? MVC stands for model-view-controller, and it’s an architecture that aims to separate out the data (model), the display (view), and the application logic (controller). This separation aims to remove any tight coupling between the components, theoretically making code more maintainable and reusable. A bonus is that these components fit very nicely into our rapid prototype development approach and allow us to concentrate on one aspect at a time as we discuss each part of the MEAN stack.

There are whole books dedicated to the nuances of MVC, but we’re not going to go into that depth here. We’ll keep the discussion of MVC at a high level, and see how we can use it with Express to build our Loc8r application.

3.3.1. A bird’s eye view of MVC

Most applications or sites that you build will be designed to take an incoming request, do something with it, and return a response. At a simple level, this loop in an MVC architecture works like this:

  1. A request comes into the application.
  2. The request gets routed to a controller.
  3. The controller, if necessary, makes a request to the model.
  4. The model responds to the controller.
  5. The controller sends a response to a view.
  6. The view sends a response to the original requester.

In reality, depending on your setup, the controller may actually compile the view before sending the response back to the visitor. The effect is the same though, so keep this simple flow in mind as a visual for what will happen in our Loc8r application. See figure 3.5 for an illustration of this loop.

Figure 3.5. Request–response flow of a basic MVC architecture

Figure 3.5 highlights the individual parts of the MVC architecture and how they link together. It also illustrates the need for a routing mechanism along with the model, view, and controller components. So now that you’ve seen how we want the basic flow of our Loc8r application to work, it’s time to modify the Express setup to make this happen.

3.3.2. Changing the folder structure

If you look inside the newly created Express project in the loc8r folder, you should see a file structure including a views folder, and even a routes folder, but no mention of models or controllers. Rather than going ahead and cluttering up the root level of the application with some new folders, let’s keep things tidy with one new folder for all of our MVC architecture. Follow three quick steps here:

  1. Create a new folder called app_server.
  2. In app_server create two new folders called models and controllers.
  3. Move the views and routes folders from the root of the application into the app_server folder.

Figure 3.6 illustrates these changes and shows the folder structures before and after the modifications.

Figure 3.6. Changing the folder structure of an Express project into an MVC architecture

Now we have a really obvious MVC setup in the application, which makes it easier to separate our concerns. But if you try to run the application now it won’t work, as we’ve just broken it. So let’s fix it. Express doesn’t know that we’ve added in some new folders, or have any idea what we want to use them for. So we need to tell it.

3.3.3. Using the new views and routes folders

The first thing we need to do is tell Express that we’ve moved the views and routes folders, because Express will be looking for folders and files that no longer exist.

Using the new views folder location

Express will be looking in /views but we’ve just moved it to /app_server/views. Changing it’s really simple. In app.js find the following line:

app.set('views', path.join(__dirname, 'views'));

and change it to the following (modifications in bold):

app.set('views', path.join(__dirname, 'app_server', 'views'));

Our application still won’t work just yet because we’ve moved the routes, so let’s tell Express about them too.

Using the new routes folder location

Express will be looking in /routes but we’ve just moved it to /app_server/routes. Changing this is also really simple. In app.js find the following lines:

var routes = require('./routes/index');
var users = require('./routes/users');

and change them to the following (modifications in bold):

var routes = require('./app_server/routes/index');
var users = require('./app_server/routes/users');

If you save this and run the application again, you’ll find that we’ve fixed it and the application works once more!

3.3.4. Splitting controllers from routes

In a default Express setup, controllers are very much part of the routes, but we want to separate them out. Controllers should manage the application logic, and routing should map URL requests to controllers.

Understanding route definition

To understand how routes work let’s take a look at the route already set up for delivering the default Express homepage. Inside index.js in app_server/routes you should see the following code snippet:

In the code at you can see router.get('/', which is where the router looks for a get request on the homepage URL path, which is just '/'. The anonymous function that runs the code is really the controller. This is a very basic example with no application code to speak of. So and are the pieces we want to separate here.

Rather than diving straight in and putting the controller code into the controllers folder, we’ll test out the approach in the same file first. To do this, we can take the anonymous function from the route definition and define it as a named function. We’ll then pass the name of this function through as the callback in the route definition. Both of these steps are in the following listing, which you can put into place inside app_server/routes/index.js.

Listing 3.2. Taking the controller code out of the route: step 1

If you refresh your homepage now it should still work just as before. We haven’t changed anything in how the site works, just moved a step toward separating concerns.

Understanding res.render

We’ll look at this more in chapter 4, but render is the Express function for compiling a view template to send as the HTML response that the browser will receive. The render method takes the name of the view template and a JavaScript data object in the following construct:

Note that the template file doesn’t need to have the file extension suffix, so index.jade can just be referenced as index. You also don’t need to specify the path to the view folder because you’ve already done this in the main Express setup.

Now that we’re clear about how the route definition works, it’s time to put the controller code into its proper place.

Moving the controller out of the routes file

In Node, to reference code in an external file you create a module in your new file and then require it in the original file. See the following sidebar for some overarching principles behind this process.

Creating and using Node modules

Taking some code out of a Node file to create an external module is fortunately pretty simple. In essence, you create a new file for your code, choose which bits of it you want to expose to the original file, and then require your new file in your original file.

In your new module file you expose the parts of the code that you wish to by using the module.exports method, like so:

module.exports = function () {
  console.log("This is exposed to the requester");
};

You’d then require this in your main file like so:

require('./yourModule');

If you want your module to have separate named methods exposed, then you can do so by defining them in your new file in the following way:

module.exports.logThis = function(message){
  console.log(message);
};

To reference this in your original file you need to assign your module to a variable name, and then invoke the method. For example, in your main file

var yourModule = require('./yourModule');
yourModule.logThis("Hooray, it works!");

This assigns your new module to the variable yourModule. The exported function logThis is now available as a method of yourModule.

When using the require function, note that you don’t need to specify a file extension. The require function will look for a couple of things: a JavaScript file of the same name or an index.js file inside a folder of the given name.

So the first thing we need to do is create a file to hold the controller code. Create a new file called main.js in app_server/controllers. In this file we’ll create an export method called index and use it to house the res.render code as shown in the following listing.

Listing 3.3. Setting up the homepage controller in app_server/controllers/main.js

That’s all there is to creating the controller export. The next step is to require this controller module in the routes file so that we can use the exposed method in the route definition. The following listing shows how the main routes file index.js should now look.

Listing 3.4. Updating the routes file to use external controllers

This links the route to the new controller by “requiring” the controller file and referencing the controller function in the second parameter of the router.get function .

We now have the routing and controller architecture, as illustrated in figure 3.7, where app.js requires routes/index.js, which in turn requires controllers/main.js.

Figure 3.7. Separating the controller logic from the route definitions

If you test this out now in your browser, you should see that the default Express home-page displays correctly once again.

That’s everything set up with Express for now, so it’s almost time to start the building process. But before that there are a couple more things that we need to do, first of which is adding Twitter Bootstrap to the application.

3.4. Import Bootstrap for quick, responsive layouts

As discussed in chapter 1, our Loc8r application will make use of Twitter’s Bootstrap framework to speed up the development of a responsive design. We’ll also make the application stand out by using a theme. The aim here is to help us keep moving forward quickly with building the application, and not get side-tracked with the semantics of developing a responsive interface.

3.4.1. Download Bootstrap and add it to the application

Instructions for downloading Bootstrap, getting a custom theme, and adding the files into the project folder are all found in appendix B. A key point here’s that the Bootstrap files are all static files to be sent directly to the browser; they don’t need any processing by the Node engine. Your Express application will already have a folder for this purpose: the public folder. When you have it ready, the public folder should look something like figure 3.8.

Figure 3.8. Structure of the public folder in the Express application after adding Bootstrap

Bootstrap also requires jQuery for some of the interactive components to load. You can reference it directly from a CDN, but we’ll download it at http://jquery.com/download/ so that we’ve got it in our application. We’re going to use the latest 1.x version, which at the time of writing is 1.11.1. So go ahead and download jQuery, saving it in the public/javascripts folder of the application.

3.4.2. Using Bootstrap in the application

Now that all of the Bootstrap pieces are sitting in the application, it’s time to hook it up to the front end. This means taking a look at the Jade templates.

Working with Jade templates

Jade templates are often set up to work by having a main layout file that has defined areas for other Jade files to extend. This makes a great deal of sense when building a web application, because there are often many screens or pages that have the same underlying structure with different content in the middle.

This is how Jade appears in a default Express installation. If you look in the views folder in the application you’ll see two files, layout.jade and index.jade. The index.jade file is controlling the content for the index page of the application. Open it up, and there’s not much in there; the entire contents are shown in the following listing.

Listing 3.5. The complete index.jade file

There’s more going on here than meets the eye. Right at the top of the file is a statement declaring that this file is an extension of another file , in this case the layout file. Following this is a statement defining a block of code that belongs to a specific area of the layout file, an area called content in this instance. Finally, there’s the minimal content that’s displayed on the Express index page, a single <h1> tag and a single <p> tag .

There are no references to <head> or <body> tags here, nor any stylesheet references. These are all handled in the layout file, so that’s more likely where you want to go to add in global scripts and stylesheets to the application. Open up layout.jade and you should see something similar to the following listing.

Listing 3.6. Default layout.jade file

Listing 3.6 shows the layout file being used for the basic index page in the default Express installation. You’ll see that there’s a head section and a body section, and within the body section there’s a block content line with nothing inside it. This named block can be referenced by other Jade templates, such as the index.jade file in listing 3.5. The block content from the index file gets pushed into the block content area of the layout file when the views are compiled.

Adding Bootstrap to the entire application

If you want to add some external reference files to the entire application, then using the layout file makes sense in the current setup. So in layout.jade you need to accomplish four things:

  • Reference the Bootstrap CSS file.
  • Reference the Bootstrap JavaScript file.
  • Reference jQuery, which Bootstrap requires.
  • Add viewport metadata so that the page scales nicely on mobile devices.

The CSS file and the viewport metadata should both be in the head of the document, and the two script files should be at the end of the body section. The following listing shows all of this in place in layout.jade, with the new lines in bold.

Listing 3.7. Updated layout.jade including Bootstrap references

With that done, any new template that you create will automatically have Bootstrap included and will scale on mobile devices—as long as your new templates extend the layout template, of course.

Finally, before testing it all out, delete the contents of the style.css file in /public/stylesheets/. This will prevent the default Express styles from overriding the Bootstrap files. We’ll want to add our own styles in to the Loc8r application somewhere a little later down the line, so there’s no need to delete the file.

Verify that it works

If the application isn’t already running with nodemon, start it up and view it in your browser. The content hasn’t changed, but the appearance should have. You should now have something looking like figure 3.9.

Figure 3.9. Bootstrap theme having an effect on the default Express index page

Remember you can get the source code of the application so far from GitHub on the chapter-03 branch. In a fresh folder in terminal the following command will clone it:

$ git clone -b chapter-03 https://github.com/simonholmes/getting-MEAN.git

Now we’ve got something working locally; let’s see how we can get it running on a live production server.

3.5. Make it live on Heroku

A common perceived headache with Node applications is deploying them to a live production server. We’re going to get rid of that headache early on and push our Loc8r application onto a live URL already. As we iterate and build it up we can keep pushing out the updates. For prototyping this is great because it makes it really easy to show our progress to others.

As mentioned in chapter 1 there are a few platform as a service providers such as Google Cloud Platform, Nodejitsu, OpenShift, and Heroku. We’re going to use Heroku here, but there’s nothing stopping you from trying out other options.

3.5.1. Getting Heroku set up

Before you can use Heroku, you’ll need to sign up for a free account and install the Heroku Toolbelt on your development machine. Appendix B has more detailed information on how to do this. You’ll also need a bash-compatible terminal; the default terminal for Mac users is fine, but the default CLI for Windows users won’t do. If you’re on Windows you’ll need to download something like the GitHub terminal, which comes as part of the GitHub desktop application.

Once you have everything set up, we can continue and get the application ready to push live.

Updating package.json

Heroku can run applications on all different types of codebases, so we need to tell it what our application is running. As well as telling it that we’re running a Node application using npm as the package manager, we need to tell it which version we’re running to ensure that the production setup is the same as the development setup.

If you’re not sure which versions of Node and npm you’re running you can find out with a couple of terminal commands:

$ node --version
$ npm --version

At the time of writing, these commands return v4.2.1 and 2.2.0, respectively. Using the ~ syntax to add a wildcard for a patch version as you’ve seen previously, you need to add these to a new engines section in the package.json file. The complete updated package.json file is shown in the following listing, with the added section in bold.

Listing 3.8. Adding an engines section to package.json

When pushed up to Heroku, this will tell Heroku that our application uses the latest patch version of Node, 4.2, and the latest patch version of npm, 2.2.

Creating a Procfile

The package.json file will tell Heroku that the application is a Node application, but it doesn’t tell it how to start it. For this we need to use a Procfile. A Procfile is used to declare the process types used by our application, and the commands used to start them.

For Loc8r we want a web process, and we want it to run the Node application. So in the root folder of the application create a file called Procfile—this is case-sensitive and has no file extension. Enter the following line into the Procfile file:

web: npm start

When pushed up to Heroku, this file will simply tell Heroku that the application needs a web process and that it should run npm start.

Testing it locally with Foreman

The Heroku Toolbelt comes with a utility called Foreman. We can use Foreman to verify our setup and run our application locally before pushing the application up to Heroku. If the application is currently running, stop it by pressing Ctrl-C in the terminal window running the process. Then in the terminal window enter the following command:

$ foreman start

All being well with the setup, this will start the application running on localhost again, but this time on a different port: 5000. The confirmation you get in terminal should be along these lines:

16:09:01 web.1  | started with pid 91976
16:09:02 web.1  | > [email protected] start /path/to/your/application/folder
16:09:02 web.1  | > node./bin/www

If you fire up a browser and head over to localhost:5000—note that the port is 5000 instead of 3000—you should be able to see the application up and running once again.

Now that we know the setup is working it’s time to push our application up to Heroku.

3.5.2. Pushing the site live using Git

Heroku uses Git as the deployment method. If you already use Git you’ll love this approach; if you haven’t you may feel a bit apprehensive about it, as the world of Git can be quite complex. But it doesn’t need to be, and once you get going you’ll love this approach too!

Storing the application in Git

The first action is to store the application in Git, on your local machine. This is a three-step process, as you need to

  1. Initialize the application folder as a Git repository.
  2. Tell Git which files you want to add to the repository.
  3. Commit these changes to the repository.

This might sound complex, but it really isn’t. You just need a single short terminal command for each step. If the application is running locally, stop it in terminal (Ctrl-C). Then, ensuring you’re still in the root folder of the application, stay in terminal and run the following commands:

These three things together will create a local Git repository containing the entire codebase for the application. When we go to update the application later on, and we want to push some changes live, we’ll use the second two commands, with a different message, to update the repository.

Your local repository is now ready. It’s time to create the Heroku application.

Creating the Heroku application

This next step will create an application on Heroku, as a remote Git repository of your local repository. All this is done with a single terminal command:

$ heroku create

When this is done, you’ll see a confirmation in terminal of the URL that the application will be on, the Git repository address, and the name of the remote repository. For example

http://shrouded-tor-1673.herokuapp.com/ | [email protected]:shrouded-tor-1673.git
Git remote heroku added

If you log in to your Heroku account in a browser you’ll also see that the application exists there. So you now have a container on Heroku for the application, and the next step is to push the application code up.

Deploying the application to Heroku

By now you have the application stored in a local Git repository, and you’ve created a new remote repository on Heroku. The remote repository is currently empty, so you need to push the contents of your local repository into the heroku remote repository.

If you don’t know Git, there’s a single command to do this, which has the following construct:

This command will push the contents of your local Git repository to the heroku remote repository. Currently, you only have a single branch in your repository, which is the master branch, so that’s what you’ll push to Heroku. See the following sidebar for more information on Git branches.

When you run this, terminal will display a load of log messages as it goes through the process, eventually ending up with a confirmation that the application has been deployed to Heroku. This will be something like the following, except you’ll have a different URL of course:

http://shrouded-tor-1673.herokuapp.com deployed to Heroku
What are Git branches?

If you just work on the same version of the code and push it up to a remote repository like Heroku or GitHub periodically, you’re working on the master branch. This is absolutely fine for linear development with just one developer. If you have multiple developers or your application is already published, then you don’t really want to be doing your development on the master branch. Instead, you start a new branch from the master code in which you can continue development, add fixes, or build a new feature.

When work on a branch is complete it can be merged back into the master branch.

Starting a web dyno on Heroku

Heroku uses the concept of dynos for running and scaling an application. The more dynos you have, the more system resources and processes you have available to your application. Adding more dynos when your application gets bigger and more popular is really easy.

Heroku also has a great free tier, which is perfect for application prototyping and building a proof-of-concept. You get one web dyno for free, which is more than adequate for our purposes here. Before you can view the application online you need to add a single web dyno. This is easily done with a simple terminal command:

$ heroku ps:scale web=1

When you’ve run this, terminal will display a confirmation:

Scaling web dynos... done, now running 1

Now let’s check out the live URL.

Viewing the application on a live URL

Everything is now in place, and the application is live on the internet! You can see it by typing in the URL given to you in the confirmation, via your account on the Heroku website, or by using the following terminal command:

$ heroku open

This will launch the application in your default browser, and you should see something like figure 3.10.

Figure 3.10. MVC Express application running on a live URL

Your URL will be different, of course, and within Heroku you can change it to use your domain name instead of the address it has given you. In the application settings on the Heroku website you can also change it to use a more meaningful subdomain of herokuapp.com.

Having your prototype on an accessible URL is very handy for cross-browser and cross-device testing, as well as sending it out to colleagues and partners.

A simple update process

Now that the Heroku application is set up, updating it will be really easy. Every time you want to push some new changes through, you just need three terminal commands:

That’s all there’s to it, for now at least. Things might get a bit more complex if you have multiple developers and branches to deal with, but the actual process of pushing the code to Heroku using Git remains the same.

3.6. Summary

In this chapter we’ve covered

  • Creating a new Express application
  • Managing application dependencies with npm and the package.json file
  • Modifying Express to meet an MVC approach to architecture
  • Routes and controllers
  • Creating new Node modules
  • Publishing an Express application live onto Heroku using Git

In the next chapter you’ll get to know Express even more when we build out a prototype of the Loc8r application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.122.162