Introducing the Express.js framework for node.js

Up to this point in the Knowing Node series we have used node.js to create a server, built a rudimentary MVC framework, and served a webpage pulling data from a MongoDB database. We used Mongoose to make working with the database easier, and now we’re going to look at a way of making the basic server and framework setup easier. Say hello to Express!

What is Express?

Express is a popular web application framework for node. The first thing you’ll enjoy is that it simplifies the web server setup – including routing for static files – and creates a directory structure as a start point for organising your  code.

We’re going to use it as we’re looking at building a web application, whether that’s a one page app or a multipage site isn’t important right now.

Installing Express

First of all we need to install Express globally. So in terminal:

sudo npm install -g express

Creating a project

Now that we’ve got Express installed globally, we let’s use it to create a new project. Here’s we create a new folder for our Express project, and install Express and it’s dependencies.

mkdir testpage-express cd testpage-express express #this installs an instance of express into the directory using the default options npm install #this installs the dependcies

You can override some of the default install options when creating a new project, for example to specify a different HTML templating engine or CSS compiler.

See the official Excpress.js guide for more info.

Start the project and view it in a browser

In terminal:

node app

This should display a confirmation in terminal “Express server listening on port 3000″. 3000 is the default port used by Express, so head over to localhost:3000 in your browser and you should see something like this:

Default Express js site on node.js

Nice. That was pretty easy right?

If you look at the page you may notice that it’s not using the default browser font, meaning there must be a stylesheet included.

Take a look back into the terminal that you use to start the process and you should see confirmation that it has delivered the URL ‘/’ and the stylesheet ‘/stylesheets/style.css’.
Terminal window confirming Express.js routes

So there we go, a few terminal commands and you’ve got a node.js webserver and framework in place. More excitingly we’ve got that basis for a web-app just waiting for us!

Next time we’ll take a look under the hood and build our simple site in Express, using the built in routing and template engines.

Get the source code

The source code for this and my other tutorials on Node.js is available on GitHub here: