Node.js app from scratch - Getting started

09 Sep 2013

This is my first deep dive into Node.

My starting point was this example code from nodejs.org:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Next I created an index.html file with a basic bootstrap template.

Scheduler App

I added the base for the calendar view and immediately wanted to take advantage of programming to fill out the hours/day matrix. But before going any further I wanted to serve this file with Node.

I looked up how to open and read files with fs on the node.js API documentation.

var fs = require('fs');
fs.readFile('/etc/passwd', function (err, data) {
  if (err) throw err;
  console.log(data);
});

This basic example gave me enough to write this:

http.createServer(function (req, res) {
  fs.readFile('index.html', function (err, data) {
    if (err) return console.log(err);
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    res.end();
  });
}).

And voila! It works… well, kind of. The index file loads without any style whatsoever, and to be honest I was puzzled and wondering how to move forward.

Scheduler App

Node is much lower level than the tools I've used before, so it took me some reading and pondering to get accustomed to it.

Every asset called from the index.html file makes a request to our Node server. This is key, so read that line twice if you need to. This means that <link href="vendor/css/bootstrap.css" rel="stylesheet"> will make a request that our server must be prepared to handle.

Once I understood this, I changed my code to serve any asset relative to my server directory:

/* The https://npmjs.org/package/mime library
 maps a filename to its appropriate mime type. */
var mime = require('mime');
var filename = '.' + request.url; // '/index.html', '/css/bootstrap.css', etc.
fs.readFile(filename, function(err, data) {
  if (err) return console.log(err);
  response.writeHead(200, { 'Content-Type': mime.lookup(filename) });
  response.write(data);
  response.end();
});

And this time it really works :)

(Note the url in the address bar)

Scheduler App

You can see the app's source code and follow my progress here: github.com/jassa/scheduler