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"; console.log('*Starting'); 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) { response.writeHead(500); response.end(); } else { response.writeHead(200, { 'Content-Type': 'application/x-gzip' }); response.end(content); }}); } else { response.writeHead(404); response.end(); }}); }).listen(8010); console.log('Server running at http://127.0.0.1:8010/');
I fired up the server:
node webserver.js
And opened my Safari browser to request a file I had dropped in my root directory.
Which works perfectly. Output on cli:
*Starting Server running at http://127.0.0.1:8010/ 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.
.nick