Node Tutorial Part 10

2011-01-24 00:00:00 +0000 by Alex R. Young

Welcome to part 10 of Let's Make a Web App, a tutorial series about
building a web app with Node. This series will
walk you through the major areas you'll need to face when building your
own applications. These tutorials are tagged with

Previous tutorials:


It would be nice if our notepad app allowed some form of markup. There
are a few markdown libraries available through npm, but
markdown seems to be quite popular.

Install it like this:

npm install markdown

It's easy to use:

var markdown = require('markdown').markdown;
markdown.toHTML('# Welcome\n\nThis is markdown');

// => 'Welcome\n\nThis is markdown'

I updated Nodepad's dependencies to include this in the
package.json file:

// ...
"dependencies": {
  "express": "1.0.0",
  "mongoose": "0.0.4",
  "connect-mongodb": "0.1.1",
  "jade": "0.6.0",
  "markdown": "0.2.0"

Then near the top of
app.js I added the require:

var express = require('express@1.0.0'),
    app = module.exports = express.createServer(),
    mongoose = require('mongoose@0.0.4').Mongoose,
    mongoStore = require('connect-mongodb@0.1.1'),
    markdown = require('markdown').markdown,
// ...

I've added a html format option for GET
which contains the markdown renderer:

// Read document
app.get('/documents/:id.:format?', loadUser, function(req, res, next) {
  Document.findById(req.params.id, function(d) {
    if (!d) return next(new NotFound('Document not found'));

    switch (req.params.format) {
      case 'json':

      case 'html':

        res.render('documents/show.jade', {
          locals: { d: d, currentUser: req.currentUser }

Visiting a valid document ID with '.html' will now render HTML using
markdown. This is easy to access using a quick \$.get call.
I've added another link next to the Save button
(#html-button) which toggles the rendered markdown view in a div:

$('#html-button').click(function() {
  var container = $('#html-container');
  if (container.is(':visible')) {
  } else {
    var id = $('#document-list .selected').itemID();
    $.get('/documents/' + id + '.html', function(data) {
      // Saved, will return JSON

This uses jQuery's is() to detect if the markdown container
is visible, and adds a class name to the button which can be styled to
indicate that the markdown display can be toggled. It looks like this:

Delete Button

The layout has changed since early on in this series, so I've changed
the delete code to work with the new layout. It just uses the same
jQuery with an updated URL for the \$.post.


Adding markdown or textile support to Node apps is pretty easy now there
are a few easily installable modules through npm. If you want to check
the commit for this part of the project, it's available at