From 5524d2b0fb9b87ef0d1beec092337f836a1043a8 Mon Sep 17 00:00:00 2001 From: Elliott Sprehn Date: Wed, 27 Oct 2010 19:06:40 -0700 Subject: Check if file exists (not a 404) and that document is accessible and not using file:// URLs in Application --- lib/nodeserver/server.js | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) (limited to 'lib/nodeserver') diff --git a/lib/nodeserver/server.js b/lib/nodeserver/server.js index 08f13a99..f91f6afa 100644 --- a/lib/nodeserver/server.js +++ b/lib/nodeserver/server.js @@ -8,10 +8,8 @@ var DEFAULT_PORT = 8000; function main(argv) { new HttpServer({ - 'GET': (function() { - var servlet = new StaticServlet(); - return servlet.handleRequest.bind(servlet) - })() + 'GET': createServlet(StaticServlet), + 'HEAD': createServlet(StaticServlet) }).start(Number(argv[2]) || DEFAULT_PORT); } @@ -22,6 +20,11 @@ function escapeHtml(value) { replace('"', '"'); } +function createServlet(Class) { + var servlet = new Class(); + return servlet.handleRequest.bind(servlet); +} + /** * An Http server implementation that uses a map of methods to decide * action routing. @@ -61,11 +64,10 @@ HttpServer.prototype.handleRequest_ = function(req, res) { } }; - /** * Handles static content. */ -function StaticServlet() {} +function StaticServlet() {} StaticServlet.MimeMap = { 'txt': 'text/plain', @@ -164,13 +166,17 @@ StaticServlet.prototype.sendFile_ = function(req, res, path) { 'Content-Type': StaticServlet. MimeMap[path.split('.').pop()] || 'text/plain' }); - file.on('data', res.write.bind(res)); - file.on('close', function() { + if (req.method === 'HEAD') { res.end(); - }); - file.on('error', function(error) { - self.sendError_(req, res, error); - }); + } else { + file.on('data', res.write.bind(res)); + file.on('close', function() { + res.end(); + }); + file.on('error', function(error) { + self.sendError_(req, res, error); + }); + } }; StaticServlet.prototype.sendDirectory_ = function(req, res, path) { @@ -207,6 +213,10 @@ StaticServlet.prototype.writeDirectoryIndex_ = function(req, res, path, files) { res.writeHead(200, { 'Content-Type': 'text/html' }); + if (req.method === 'HEAD') { + res.end(); + return; + } res.write('\n'); res.write('