Proving a another guy’s point : MacBook Air & Node.js as a Webserver

Ok, this is a real quick example of someone else’s idea. Namely Christofer Hoff of Juniper (infamous blog & twitter account) who in response to my tweet about my MacBook and a webserver (I am a Mac-newbie). Suggested I try using Node.js.


At first I was a little taken back. I think @Beaker thought I didn’t get the point (and I don’t more than I do).


So I *cheated* and just turned on Web Sharing with the good tips from my other twitter buddies. But the Node.js idea bugged me because technically Chris is right. It should work fine.

So I did it. I installed the Node.js package for OSX (been using the Linux version) and fired up TextEdit and wrote this simple bit of code:

var http = require('http');
var fs = require('fs');
var path = require('path');
var rootpath = "/Users/lynxbat/Webroot";

http.createServer(function (request, response) {
 console.log('Server started');
 var pathToFile = rootpath + request.url;
 console.log ('File was requested: ' + pathToFile);
 path.exists(pathToFile, function(exists) {
 if (exists) {
  fs.readFile(pathToFile, function(error, content) {
   if (error) {
   } else {
    response.writeHead(200, { 'Content-Type': 'application/x-gzip' });
   } else {
console.log('Server running at');

I fired up the server:

node webserver.js

And opened my Safari browser to request a file I had dropped in my root directory.

Screen Shot 2011-12-19 at 4.18.55 PM

Which works perfectly. Output on cli:

Server running at
Server started
File was requested: /Users/lynxbat/Webroot/node-v0.6.6.pkg

Now in my case I am using the Webserver to hand out packages for installing as a local mirror for some VM’s I am building (big demo for Jan). So I hardcoded the MIME type and left response encoding unset. If you were looking to properly serve you should perhaps add some logic for switching types and responses based on the file extension. Kind of like a proper web server works.

So Chris was right. This works. Though I think proving him right probably isn’t a good habit to pick up.


Cloud Life/Work Scripts Tools

5 Comments Leave a comment

    • Yup – that is what happens when you run interactive stuff under your username.

      But, should someone actually want to do this a proper WWW user with a restricted path would be cool. Or just filtering ‘../’ in the request also.

%d bloggers like this: