How to use Node.js to build pages that are a mix between static and dynamic content?


Question

All pages on my 5 page site should be output using a Node.js server.

Most of the page content is static. At the bottom of each page, there is a bit of dynamic content.

My node.js code currently looks like:

var http = require('http'); 

http.createServer(function (request, response) {

    console.log('request starting...');

    response.writeHead(200, { 'Content-Type': 'text/html' });

    var html = '<!DOCTYPE html><html><head><title>My Title</title></head><body>';
    html += 'Some more static content';
    html += 'Some more static content';
    html += 'Some more static content';
    html += 'Some dynamic content';
    html += '</body></html>';

    response.end(html, 'utf-8');

}).listen(38316);

I'm sure there are numerous things wrong about this example. Please enlighten me! For example:

  • How can I add static content to the page without storing it in a string as a variable value with += numerous times?
  • What is the best practices way to build a small site in Node.js where all pages are a mix between static and dynamic content?
1
39
5/25/2011 3:02:46 PM

Accepted Answer

Personally, I'd use a server that has higher level constructs. For instance, take a look at the expressjs framework - http://expressjs.com/

The constructs you'll be interested in from this package are:

For example in jade:

!!! 5
html(lang="en")
  head
    title= pageTitle
    script(type='text/javascript')
      if (foo) {
         bar()
      }
  body
    h1 Jade - node template engine
    #container
      - if (youAreUsingJade)
        p You are amazing
      - else
        p Get on it!

Becomes:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Jade</title>
    <script type="text/javascript">
      if (foo) {
        bar()
      }
    </script>
  </head>
  <body>
    <h1>Jade - node template engine</h1>
    <div id="container">
      <p>You are amazing</p>
    </div>
  </body>
</html>

If you prefer something a little less drastic I would say look at mustache or one of the other engines that looks a bit more like regular-sauce html.

28
12/3/2015 2:17:30 PM

Alternative you can just use jsDOM. This means you have a DOM object you can manipulate on the server to add your dynamic content, then you can just flush the DOM as a HTML file / string


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon