Create A Simple Web Application With Express.js

I’ve recently been exploring other options when it comes to web frameworks. I come from a PHP ZendFramework background, but since having upgrading to ZendFramework 2, I’ve not been impressed.

Since then I’ve been exploring more of Node.js. However, like PHP, web programming often works best with a framework. This is why I’ve been exploring Node.js with Express as the framework.

Through my research, Express.js appears to be one of the best if not the best Node.js web framework available. It is lightweight, quick, and offers all the great functionality, such as routing and layouts that other frameworks offer. It also uses Jade as its template engine.

You might be like, what is Jade and why do I need to forget HTML markup to learn it? I thought the same initially, but it turns out to be much more convenient to use than HTML. We’ll get into that soon.

Let’s start by installing Express.js. I’m going to assume you already have Node.js and Node Package Manager (NPM) installed. If you don’t have it installed I suggest you stop here and go find documentation on how to install it. To install the necessary Express.js components, run the following:

sudo npm install -g express
sudo npm install -g express-generator

I used sudo because I’m on a Mac. If you’re using Windows, just omit that command.

With Express.js installed, let’s create a new project:

express TestProject

Because we installed the Express.js generator, we are left with a project and properly configured directory structure. With the project as your current directory it is time to install all the proper dependencies. This can be done by running:

npm install

You now have a very runnable project. Test out what you have by starting a local server:

The above code is what we have in our views/layout.jade file. It is similar to HTML, but instead of tag characters we use indents to signify what is inside of a tag. I found this to increase my productivity and make my code easier to read.

Check out the above code. This represents the home page route, so in our scenario if we hit http://localhost:3000, then we will end up here. A variable title will be passed to our view for displaying. In this case our view is index.jade aka index.

If you’re planning on getting into Node.js for web development, I encourage you to check out Express.js. It is quick and easy and definitely fun to play around with.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.