Creating Web Applications in JavaScript with Express.js

jeffcogswell 2 Tallied Votes 852 Views Share
Manufacturer
TJ Holowaychuk and others
URL Screenshot of http://expressjs.com http://expressjs.com
Price
Free/Open Source
Pros
Very easy to create powerful web sites. And you get to use JavaScript for your server-side processing. You can switch out the default view/templating engine to one of your choice.
Cons
Lots of work at the command line, which for me isn't a problem but some people might not like.
Summary
ExpressJS is an excellent addition to the Node.js system. It helps you quickly create web sites using JavaScript. The default view engine is a little odd, but you can switch to a different engine if you prefer.
Rating

Last week, I took a look at Node.js, a powerful server-side implementation of JavaScript. But one thing I found lacking was the way to easily create a web server. Essentially, Node is an implementation of CommonJS, which adds operating systems features to JavaScript. But Node is not a web application framework. If you want to build a web application in Node, you either need to do a lot of coding, or find a good framework that somebody else built. And that's what I found here—a framework called Express.js.

In four words: This thing is sweet. Let's take a look at it.

I've done a lot of web application development, mostly with PHP or C#/ASP.NET, so I'm able to compare express.js to those platforms. And I can say that the creators of Express.js (who includes the creator of Node.js) have done an awesome job putting this thing together.

First off, you have to download it, adding it to your Node installation. The instructions are on the web site , so I won't repeat them here, except to say that you need to follow the steps exactly as shown on the installation page. Next, you have to install a view engine called Jade (along with a replacement to Jade that I personally prefer; more on that shortly).

After all is installed, and the node installation directory is added to your path, you create a directory on your Linux box. Then, at the command prompt, simply type:

express

This creates a starting skeleton project, along with a file called app.js, as well as a set of directories and helper files:


The main file, app.js, contains a starting point for your application. And since it's running under Node, it's all JavaScript. Here it is:

/**
 * Module dependencies.
 */

var express = require('express');

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyDecoder());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.staticProvider(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 
});

app.configure('production', function(){
  app.use(express.errorHandler()); 
});

// Routes

app.get('/', function(req, res){
  res.render('index', {
    locals: {
      title: 'Express'
    }
  });
});

// Only listen on $ node app.js

if (!module.parent) {
  app.listen(3000);
  console.log("Express server listening on port %d", app.address().port)
}

Essentially this code is a series of calls into the framework. The framework object is accessible through the app variable. The calls to app.configure() set up the web application. The call to app.get() specifies a URL (in this case just /, or the root) and what to do when a browser requests that URL.

I started the server like this:

jeff@jeff-ubuntu:~/dev/daniweb$ node app.js
Express server listening on port 3000

And here's the browser window when I call up the root. (I have to add :3000 because the server is listening on port 3000.)


As I was playing with Express, I found that I wasn't comfortable with the default view engine, which is called Jade, and I decided to use an alternative. But first, what exactly is a view engine? Look at it like this: In web programming, you can write code in the language you're using, such as C# if you're working with ASP.NET, or the PHP language itself if you're working under the PHP platform. But you also need to work with HTML. Typically you'll create an HTML file and embed your code right in it alongside the HTML tags. Then you'll probably have a lot of separate code in different files that aren't intermixed with HTML.

The HTML files that have PHP or C# embedded in them are essentially views. In Express, you have different view engines you can use. The default one is called Jade, which lets you create your HTML declaratively. You can give it a try and see what you think; maybe you'll like it. I found the syntax awkward. But that's not a problem: There are many different view engines you can use at https://github.com/joyent/node/wiki/modules (look in the section called Templating). I found one called EJS that uses JavaScript syntax. So whereas in PHP, for example, you would embed PHP code within your HTML, here I can embed server-side JavaScript in my view. (Remember: We're talking server-side here, which means the JavaScript code will run on the server end before the resulting HTML is sent to the browser. And, of course, you can still have client-side JavaScript code in your files too.)

Take a look at this view. This is called index.ejs and goes in the views directory of your project:

<h1>Welcome to DaniWeb!</h1>
<p>Hello there! The current time is <%=Date()%>

This is mainly HTML, but there's a tiny bit of JavaScript embedded in it, namely this single function call:

Date()

The JavaScript is embedded inside a <% and %> tag, which tells the system this is server-side code (as opposed to the usual tags, which mean the JavaScript will be client-side). But there's also an equals sign after the opening tag, which means the output of the function will be displayed right in the web page.

Here's how it works. In the app.js file, there's a call to app.get(). This function displays the view by calling res.render(). Since I changed to a different view engine, I had to make a few changes to app.js. First, I replaced this line in the configure call:

app.set('view engine', 'jade');

with this line:

app.set('view engine', 'ejs');

And then I replaced the entire call to app.get() with this:

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

This means when the browser requests the root, as in /, the code will render the view called index.ejs. (The extension isn't included since it's specified with the view engine.) So after these changes—updating the call to the view engine, changing the app.get() call, and creating the index.ejs file, here's what you get.


To understand the view concept even more, check out this example. In the app.js file, look at the app.get() functions. You call that function over and over, passing the relative web addresses that you want to respond to. Look at this one that I added:

app.get('/forum', function(req, res){
  res.render('forum', { locals: {
    forums: ['php','C++','linux','windows']
  }});
});

The first parameter to app.get() is '/forum'. The second parameter is a handler function, and that function will get called when the URL /forum is requested by the browser. (Note that you can also use wildcards. I'll give a quick example for that shortly.) Inside the handler function, I'm displaying a view I created called forum. But I'm also passing some variables into the view. I've hardcoded a few, but you can get these from anywhere, either calculated or found in a database, or anything you want. Here's the forum.ejs view file I made:

<body>
<h1>Header 1</h1>
<p>Hello there</p>
Length: <%= names.length %>
<div>
  <ul>
    <% names.forEach(function(name){ %>
      <li><%= name %></li>
    <% }) %>
  </ul>
</div>
</body>

This is mostly HTML, except notice there's some JavaScript embedded in it, including an iteration through the forums variable that was passed in. And here's a screen shot of what you get:


Master Files

Now you might be wondering why I started the HTML with a tag and not an tag. That's because there's an additional view file called layout.ejs that you have to create, and it acts as a wrapper around your views. You can put any HTML you want in it. Here's the one I created:

<html>
<body>
<%-body%>
</body>
</html>

The view system starts with this file, and inserts the specific view file--in this case, forum.ejs--in place of the <%-body%> tag. This way you can accomplish a theme or master file of sorts.

Conclusion

This is just a very brief look at express.js, and by no means comprehensive. There's a ton of features in it, probably enough to fill a book. But all in all, I have to say I'm impressed. I like what I see. JavaScript is a flexible, powerful language, and I love that I can use it in three places now -- in my server-side programming, in my views, and, of course, in the client/browser-side. The with express.js, I get a nice framework for easily putting together web pages. The way you specify your URLs is especially cool. Now I'm going to try building an entire web site with it.

kvprajapati commented: nice post! +12