From cbc9f5d17c43d85dfbe1b4581d415f303d046ebd Mon Sep 17 00:00:00 2001 From: Jeff Gold Date: Wed, 15 Jul 2015 18:33:45 -0400 Subject: [PATCH] server.js: use strict --- server.js | 89 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 49 insertions(+), 40 deletions(-) diff --git a/server.js b/server.js index bb68ad8..40daf93 100755 --- a/server.js +++ b/server.js @@ -1,47 +1,56 @@ #! /usr/bin/env node // Quick-and-dirty web server using Node.js // Republic Of Techies (RoT) group project. -var sys = require('sys'); -var http = require('http'); -var fs = require('fs'); -var path = require('path'); -var port = 8080; +(function() { + 'use strict'; -http.createServer(function(request, response) { - var url = request.url; - if (url === '/') - url = '/index.html'; + var sys = require('sys'); + var http = require('http'); + var fs = require('fs'); + var path = require('path'); + var port = 8080; - if (url === '/time') { - response.writeHeader(200, { - "Context-Type": "text/plain", - "Access-Control-Allow-Origin": "http://localhost"}); - response.write(new Date().toString()); + var respond = function(response, code, headers, data) { + response.writeHeader(code, headers); + response.write(data); response.end(); - } - - fs.readFile(path.join('.', url), function (err, data) { - if (err) { - if (err.code === 'ENOENT') { - fs.readFile('page404.html', function(err, data) { - if (err) - throw err; - response.writeHeader(404, { - "Content-Type": "text/html"}); - response.write(data.toString() - .replace(/:PATH:/g, url)); - response.end(); - }); - } else throw err; - } else { - // :TODO: determine content type -- - // by file extension? - // by contents? - // a combination of both? - response.writeHeader(200, {"Content-Type": "text/html"}); - response.write(data); - response.end(); + }; + + http.createServer(function(request, response) { + var url = request.url; + if (url === '/') + url = '/index.html'; + + if (url === '/time') { + respond(response, 200, { + "Context-Type": "text/plain", + "Access-Control-Allow-Origin": "http://localhost"}, + new Date().toString()); } - }); -}).listen(port); -console.log('Server listening: http://localhost:' + port + '/'); + + fs.readFile(path.join('.', url), function (err, data) { + if (err) { + if (err.code === 'ENOENT') { + fs.readFile( + 'page404.html', + function(err, data) { + if (err) + throw err; + respond(response, 404, { + "Content-Type": "text/html"}, + data.toString() + .replace(/:PATH:/g, url)); + }); + } else throw err; + } else { + // :TODO: determine content type -- + // by file extension? + // by contents? + // a combination of both? + respond(response, 200, { + "Content-Type": "text/html"}, data); + } + }); + }).listen(port); + console.log('Server listening: http://localhost:' + port + '/'); +})();