template for node work

2012-03-02 @ 17:52#

starting to ramp up my node-er-ing and have settled into some personal habits/standards that help me get past the 'dross' and into the heart of the puzzles.

so, i'll drop some of these items here in the blog as a way to 'out' my habits, get some feedback and refine my standards over time.

basic template for app.js

here's how i "start" my scripts:

/* hello, node */

// declare module to use
var http = require('http');

// handle all requests
function handler(req, res) {
  res.writeHead(200, 'OK',{'Content-Type':'text/plain'});
  res.end('Hello, node!  from '+ req.url);
}

// listen for requests
http.createServer(handler).listen(process.env.PORT);

a three-part model:

  1. pull in requires
  2. set up listener to run "handler" when the event fires (at the bottom)
  3. supply the "handler" (as the actual function name)

some additional decoration

for non-trivial examples, i usually declare a module-level hash table (the use of the hash is a sanity check for my mental REPL when trying to resolve scope).

i also write a main(); to hold the routing logic or other high-level stuff. this is not needed, but again, keeps the code clean and sectioned off.

/* hello form */

// modules
var http = require('http');
var querystring = require('querystring');

function handler(req, res) {

  var g = {};
  g.url = '/';
  g.textHtml = {'Content-Type':'text/html'};
  g.form = '<h1>hello, form!</h1>'
    + '<form method="post" action="/" >'
    + '<label>Email: </label>'
    + '<input name="email" type="email" value="" placeholder="user@example.org" required="true" />'
    + '<input type="submit" />'
    + '</form>';
  g.output = '<h1>hello, form!</h1>'
    + '<p>{@email}</p>'
    + '<p><a href="/">return</a></p>'

  main();

  function main() {
    if(req.url === g.url) {
      switch(req.method) {
      case 'GET':
        handleGet();
        break;
      case 'POST':
        handlePost();
        break;
      default:
        sendResponse(405, 'Method not allowed', '<h1>405 - Method not allowed</h1>');
      }
    }
    else {
      sendResponse(404, 'Not found', '<h1>404 - Not found</h1>');
    }
  }

  function handleGet() {
    sendResponse(200, 'OK', g.form);
  }

  function handlePost() {
    var body = '';

    req.on('data', function(chunk) {
      body += chunk.toString();
    });

    req.on('end', function() {
      var results = querystring.parse(body);
      sendResponse(200, 'OK', g.output.replace('{@email}',results.email));
    });
  }

  function sendResponse(status, text, body) {
    res.writeHead(status, text, g.textHtml);
    res.end(body);
  }

}

http.createServer(handler).listen(process.env.PORT);

comments, suggestions, warnings?

any feedback you wish to share?

nodejs