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:
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.