208
2p
2d-particle-experiements / files
2d-particle-experiements / node.js
2.4 KB
1/*jslint node:true, nomen:true */ 2(function () { 3 'use strict'; 4 var _http = require('http'), 5 _path = require('path'), 6 _fs = require('fs'), 7 _url = require('url'), 8 PORT = 8080, 9 HTDOCS = __dirname, 10 CACHE = 0, // 1000 * 60 * 60 * 24 * 30, /* one month */ 11 EXTNAMES = { 12 'html': 'text/html', 13 'htm' : 'text/html', 14 'css' : 'text/css', 15 'js' : 'application/javascript' 16 }; 17 18 19 _http.createServer(function (req, res) { 20 var url, pathname; 21 22 /* I only want GET requests */ 23 if (req.method === 'GET') { 24 url = _url.parse(req.url, true); 25 26 /* fix / (root) request */ 27 if (url.pathname === '/') { 28 url.pathname = '/index.html'; 29 } 30 31 /* make sure we only serve files within HTDOCS */ 32 pathname = HTDOCS + url.pathname; 33 _fs.exists(pathname, function (exists) { 34 if (!exists) { /* @TODO check for .dotfiles */ 35 console.log("Error: 404.", url.pathname); 36 res.writeHead(404); 37 return res.end("Sorry, no file for you."); 38 } 39 40 pathname = _path.resolve(HTDOCS + url.pathname); 41 _fs.readFile(pathname, 'utf8', function (err, out) { 42 var extname = _path.extname(url.pathname).substring(1), 43 contentType = EXTNAMES[extname]; 44 45 if (err) { 46 console.log('Error: 500, Cannot read file', pathname); 47 res.writeHead(500); 48 res.end("Could not resolve path request"); 49 console.log(err, err.stack); 50 } 51 52 res.writeHead(200, { 53 "content-type": contentType + ", charset=UTF-8", 54 "content-length": out.length, 55 "cache-control": "public, max-age=" + CACHE 56 }); 57 res.end(out); 58 console.log('Success: 200', url.pathname); 59 }); 60 }); 61 } else { 62 console.log('Rejected'); 63 res.writeHead(405); 64 res.end('Sorry, only taking GET requests right now.'); 65 } 66 }).listen(PORT); 67 68 console.log(' === Server running === '); 69}());