​Part 2: Creating my first HTTP server in Node.js

I recently wrote about my first dive into Node.js. Here's part two where I managed to get the server to read and return the correct file includes.

This is where using a module might be more efficient, but like I said before, I want to understand how node works before I start piling on modules. I wouldn't want to ship this code, but it's suitable for prototyping.

I'm going to start by adding two more modules which are included with node. 'fs' is for accessing the file system and 'path' is for handling and transforming file paths.

var http = require('http');
var fs = require('fs');
var path = require('path');

Inside the server object I wrote the following:

var server = http.createServer(function(req, res) {
  var filePath = '.' + req.url
  if (filePath == './') {
   filePath = './index.html';
  }
  var fileExtension = path.extname(filePath);
  var contentType;
  switch (fileExtension) {
    case '.js':
    contentType = 'text/javascript';
    break;
    case '.json':
    contentType = 'application/json';
    break;
    case '.css':
    contentType = 'text/css';
    break;
    default:
    contentType = 'text/html';
  }
  fs.exists(filePath, function(exists) {
    if (exists) {
      fs.readFile(filePath, 'utf-8', function(error, data) {
        if (error) {
          res.writeHead(500, { 'Content-Type': 'text/html' });
          res.write('Uh oh, error reading that file!');
          res.end();
          console.error('Uh oh, error reading that file!', error);
          return;
       } else {
           res.writeHead(200, { 'Content-Type': contentType });
           console.log("Crikey, it works!" + contentType);
           res.end(data);
       }
     });
   } else {
       res.writeHead(404);
       res.end();
   }
 });
});
server.listen(9000);
console.log("Server is listening, yeah!");

What's this doing? First it stores the file path in the url. Then it stores the extension name of the file path. The extension name then determines the content type that will be stored with it.

The next bit is a function which reads the files and returns the correct file type. If the file requested doesn't exist, a 404 error message will be returned. The function takes two arguments: an error and the file contents. So, if there's an error reading the file, an error message will be returned and if it's successfully read, the correct file type and data will be returned.

So that's one way to set up a node site for a prototype.