-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
executable file
·71 lines (56 loc) · 1.51 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*Woodchuck Hard Cider - node.js with express*/
var express = require('express');
var app = express();
var path = require('path');
var http = require('http');
var fs = require("fs");
// all environments
app.set('port', process.env.PORT || 14631);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
http.createServer(function(req, res){
var filename = req.url;
if(req.url == "/")
filename = "/index.html";
var ext = path.extname(filename);
var localPath = __dirname;
var validExtensions = {
".html" : "text/html",
".js": "application/javascript",
".css": "text/css",
".txt": "text/plain",
".jpg": "image/jpeg",
".gif": "image/gif",
".png": "image/png"
};
var isValidExt = validExtensions[ext];
if(isValidExt) {
localPath += filename;
path.exists(localPath, function(exists){
if(exists){
console.log("serving file: " + localPath);
getFile(localPath, res, ext);
} else {
console.log('file not found: ' + localPath);
res.writeHead(404);
res.end();
}
});
} else {
console.log("Unknown file extension detected: " + ext);
}
}).listen(80);
function getFile(localPath, res, mimeType) {
fs.readFile(localPath, function(err, contents) {
if(!err) {
res.setHeader("Content-Length", contents.length);
res.setHeader("Content-Type", mimeType);
res.statusCode = 200;
res.end(contents);
} else {
res.writeHead(500);
res.end();
}
});
}