Search code examples
node.jsexpresspugpretty-print

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

  • 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 }).