How can I get Express to output nicely formatted HTML?

When using Express for Node.js, I noticed that it outputs the HTML code without any newline characters or tabs. Though it may be more efficient to download, it's not very readable during development.

How can I get Express to output nicely formatted HTML?


Solution 1:

In your main app.js or what is in it's place:

Express 4.x

if (app.get('env') === 'development') {
  app.locals.pretty = true;
}

Express 3.x

app.configure('development', function(){
  app.use(express.errorHandler());
  app.locals.pretty = true;
});

Express 2.x

app.configure('development', function(){
  app.use(express.errorHandler());
  app.set('view options', { pretty: true });
});

I put the pretty print in development because you'll want more efficiency with the 'ugly' in production. Make sure to set environment variable NODE_ENV=production when you're deploying in production. This can be done with an sh script you use in the 'script' field of package.json and executed to start.

Express 3 changed this because:

The "view options" setting is no longer necessary, app.locals are the local variables merged with res.render()'s, so [app.locals.pretty = true is the same as passing res.render(view, { pretty: true }).

Solution 2:

To "pretty-format" html output in Jade/Express:

app.set('view options', { pretty: true });

Solution 3:

There is a "pretty" option in Jade itself:

var jade = require("jade");

var jade_string = [
    "!!! 5",
    "html",
    "    body",
    "        #foo  I am a foo div!"
].join("\n");

var fn = jade.compile(jade_string, { pretty: true });
console.log( fn() );

...gets you this:

<!DOCTYPE html>
<html>
  <body>
    <div id="foo">I am a foo div!
    </div>
  </body>
</html>

I doesn't seem to be very sophisticated but for what I'm after -- the ability to actually debug the HTML my views produce -- it's just fine.