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


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');


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?
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 -

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

For example in jade:

!!! 5
    title= pageTitle
      if (foo) {
    h1 Jade - node template engine
      - if (youAreUsingJade)
        p You are amazing
      - else
        p Get on it!


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

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.

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