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.

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:

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’.

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!