Revision: 44578
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at April 14, 2011 12:54 by nikefido
Initial Code
var sys = require("sys"),
http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs");
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname;
var filename = path.join(process.cwd(), uri);
var req = false;
path.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
fs.readFile(filename, "binary", function(err, file) {
if(err) {
//If is directory, fallback to 'site index'
if(err.errno == 21) {
req = http.request({host:'localhost',port:8080,path:'/hub.html',method:'GET'}, function(res) {
res.on('data', function(chunk) {
response.writeHead(200);
response.write(chunk, 'binary'); //vs response.write(''+chunk); to cast as String
response.end();
});
});
req.end();
return;
}
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200);
response.write(file, "binary");
response.end();
});
});
}).listen(8080);
sys.puts("Server running at http://localhost:8080/");
Initial URL
Initial Description
Gives you an idea of how to fallback to an 'index' page if URL points to a directory. Not very refined - Will never return a "is directory" error
Initial Title
Nodejs server with site index fallback
Initial Tags
Initial Language
JavaScript