Node.JS 101: Querying a Database and Outputting a Dynamic HTML Table with Express and Jade

Last night I gave a presentation about “What’s New in ColdFusion 11” to our ColdFusion meetup in DC. What’s new, of course, is that Adobe has put a lot of effort into making ColdFusion a lot more like JavaScript by significantly enhancing CFScript- an alternative to the ColdFusion Markup Language (CFML) that has syntax similar to JavaScript.

Of course, CFScript isn’t JavaScript. It’s not even similar to Microsoft’s jScript (shudder). And switching between CFScript programming and JavaScript programming is a little like switching between playing ping pong and playing tennis. They’re kinda similar, but playing a lot of ping pong is likely to screw up your tennis game, and vice-versa.

The fact of the matter is that if a CF developer really wants to program in Javascript, then they should just learn to stop worrying and take a close look at Node.JS. Node.js is a platform built on Chrome’s JavaScript runtime. It’s ridiculously fast and pretty straightforward to learn – assuming that you’re already familiar with basic JavaScript concepts.

For example, let’s take a look at a bit of Node code that queries a MySQL database table and subsequently transmits the results to a JADE template:


// create the connection 
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: ''
});

var sql = 'SELECT firstName,lastName from NodeJSExamples.Person';
connection.connect();

connection.query(sql, function(err, rows, fields) {
  if (err) throw err;
  res.render('users', { title: 'Users', rows: rows });
});

connection.end();

Pretty straightforward, right?

Now let’s take a look at the code that dumps out the rows into an HTML table via the Jade templating engine:

extends layout

block content
  h1= title
  p #{title} Listing

  table
    thead
      tr
        th First Name
        th Last Name
    tbody
      - each item in rows
        tr
          td= item.firstName
          td= item.lastName

Is this syntax superior (and even less verbose) than CFScript? You be the judge. And if you find yourself intrigued by the possibilities of Node.js, check out our new, no-nonsense, one-day instructor led course – Node.JS Fundamentals!

Leave a comment