Hello World with Node, Express, and Jade

This weekend I’ve started learning the MEAN stack. In this post I will discuss how to set up a server with Node and Express, and create templates with Jade. This whole get-up looks really simple, but I’ve spent an inordinate amount of time troubleshooting and guessing at things and I hope this can help you.

This work is adapted from Bradley Daley’s Node.js MongoDB and AngularJS Web Development book. I had tried this other book, but I started running into deprecated functionality problems in chapter six. The Daley book is very thorough and helpful. I had some issues with the Jade templates, but I’ve worked them out in this example.

So, in my root folder I have app.js,

#!/usr/bin/env node
// app.js

var express = require('express'),
    http = require('http'),
    jade = require('jade') ;

var app = express() ;

app.set( 'views', './views' ) ;
app.set( 'view engine', 'jade' ) ;
app.engine( 'jade', jade.__express ) ;

app.locals = {
    title: 'Big Long Title',
    myname: 'Connor',
    hobby: 'Complooters'
} ;

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

var server = app.listen( 3000, function() {
    var host = server.address().address ;
    var port = server.address().port ;
    console.log( 'App is listening at http://%s:%s, host, port ) ;
}) ;

In a ./views/ directory I have two documents. The first is main_jade.jade,

doctype html
html
  head
    title #{title}
  body
    block content

The second is user_jade.jade

extends main_jade
block content
  h1 Level One Heading
  p Paragraph lorem ipsum etc.
  ul
    li Name #{myname}
    li Hobby: #{hobby}

What’s neat is that the user_jade.jade inserts itself into main_jade.jade and then fills in all of the #{} fields using the app.locals object in app.js. Routing and rendering is achieved through the app.get() call in app.js, and then the whole thing is hosted using the app.listen() call.