Express with Jade on node.js

Over the weekend, I was playing around with node.js – a javascript implementation of an event I/O handler. Node.js is an event based framework that allows developer to easily build scalable network programs. The framework runs on the javascript V8 engine and was influenced by by Ruby’s Event Machine and Python’s Twisted. Node.js breaks the barrier between server side language and client side language.

Node.js is very easy to use, node.js came with a neat package manager like python’s easy_install and ruby’s gem. The packages that I played around with was express – a web framework, and Jade– a template engine. Below, I will show you how to combine the two packages Jade and Express to make a web app in 5 minutes.
first, make sure you have node.js, npm, express and jade installed on your machine.

Then create a file (call it example.js) using any editor you wish, and paste the code below.


var express = require('express')
var jade = require('jade')
app = express.createServer();
var local_var = "I am a local var";
jade.renderFile('index.jade', {locals:{local_var:local_var}} ,function(err,html){
console.log("Express server is started on port %s", app.address().port);

The first two lines imports the two packages that we are going to use and gives them each a name space.

app = express.createServer();
This allows us to have a handle on a concrete server

app.get('/',function(req,res){ .....});
defines a call back on our server. Every time the url path ‘/’ of our server is queried,
the function(req,res){….} will be called.

jade.renderFile('index.jade', {locals:{local_var:local_var}} ,function(err,html){

renders the file ‘index.jade’ and pass the local variables defined in the hash {locals:{local_var:local_var}} to the template for proper variable substitution, in our case local_var (defined as “I am a local var”).
res.send(html) then sends the html that was rendered back to the client.

Our template file will look like the below. Paste it into a file in the same directory as example.js, and name this file index.jade.

p= local_var
The above basically says that the paragraph will contain the value of what ever is defined in the variable ‘local_var’.

runnning the app

$ node example.js
Express server is started on port <port>

testing if it works
curl localhost:<port>

the above should give you

<p>I am a local var</p>


  1. #1 by Jesse on April 12, 2011 - 1:56 am

    I am just jumping into node.js and this was exactly what I was looking for, thanks!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: